Python date.fromisoformat and timedelta
date.fromisoformat reads an ISO calendar date. Adding a timedelta advances the date across month and year boundaries.
A simple example
date.fromisoformat and timedelta
- Start with 2024-01-31
- Do this Add one calendar day
- Result 2024-02-01
Syntax
date.fromisoformat(text) + timedelta(days=1)
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Advance a calendar deadline by one day
A reporting or booking deadline falls close to the end of a month. Use a calendar operation and validate the input so a leap day or an invalid date cannot silently shift the deadline.
from datetime import date, timedelta
for text in ("2024-02-29", "2023-02-29"):
try:
print(date.fromisoformat(text) + timedelta(days=1))
except ValueError:
print("invalid date")
2024-03-01 invalid date
Leap-year validation happens during parsing. The valid leap day advances to March 1 and the invalid one raises ValueError before arithmetic begins.
Python documentation for date.fromisoformat and timedelta
Return a borrowed microscope
A school lends a microscope two days before the end of February in a leap year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?
Send a year-end reminder
A gallery schedules its reminder one day after the final day of the year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?