Pages

Thursday, November 19, 2026

In Python, subtract UTC instants to measure elapsed time

A support shift in New York starts at 00:30 and ends at 03:30 on the morning the clocks fall back. The wall clock shows a three-hour difference, but the shift lasts four hours. Subtracting the local Python datetimes directly can quietly give you the wrong duration.

Reproduce the difference

Use Python 3.9 or newer. If your machine lacks an IANA time-zone database, install Python's first-party tzdata package in the project environment.

from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

ny = ZoneInfo("America/New_York")
utc = timezone.utc
start = datetime(2025, 11, 2, 0, 30, tzinfo=ny)
end = datetime(2025, 11, 2, 3, 30, tzinfo=ny)

wall_clock = end - start
elapsed = end.astimezone(utc) - start.astimezone(utc)
print(start.isoformat(), "→", end.isoformat())
print("Wall-clock difference:", wall_clock)
print("Elapsed duration:", elapsed)
assert wall_clock == timedelta(hours=3)
assert elapsed == timedelta(hours=4)

The first line shows the offset changing from UTC−04:00 to UTC−05:00. The next two lines report 3:00:00 and 4:00:00, respectively. When two aware datetime values have the same tzinfo object, subtraction ignores that object. Convert the endpoints to UTC before subtracting to measure elapsed time.

Disambiguate the repeated hour

At 01:15 that morning, the local reading occurs twice. Use fold=0 for the first occurrence and fold=1 for the second.

first = datetime(2025, 11, 2, 1, 15, tzinfo=ny, fold=0)
second = first.replace(fold=1)
assert first.utcoffset() == timedelta(hours=-4)
assert second.utcoffset() == timedelta(hours=-5)
assert second.astimezone(utc) - first.astimezone(utc) == timedelta(hours=1)

For completed events, store the UTC instant and convert it for display. For an appointment that follows local time, retain the date, time and zone name. Ask which occurrence the person means if the time is repeated, and separately validate times skipped in spring; attaching ZoneInfo does not perform that validation.

References: Python datetime arithmetic and Python zoneinfo and fold.


Site affiliation: Howcodex is operated by the account sharing this standalone, tested example.

0 comments:

Post a Comment