Library contents

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

  1. Start with 2024-01-31
  2. Do this Add one calendar day
  3. Result 2024-02-01
January ends on day 31. The next day starts a new month.

Syntax

Python 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 the programprint(date.fromisoformat(text) + timedelta(days=1))
First output line2024-03-01
lesson.py
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")
Output
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

Advertisements

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?

Given28 February 2024 + 2 days
Worked result2024-03-01

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?

Given31 December 2026 + 1 day
Worked result2027-01-01