Sub topic 3
Daylight Saving Time: Gaps, Repeats, and `fold`
Assume Python 3.9 or later and that you understand aware datetimes, UTC offsets, and ZoneInfo.
Gaps and repeated times
Daylight saving time creates two unusual local-time cases:
- A gap occurs when clocks move forward. Some local times never happen.
- A fold occurs when clocks move backward. Some local times happen twice.
For example, in New York, the clock repeats 01:30 when daylight saving time ends. Python uses fold=0 for the first occurrence and fold=1 for the second.
from datetime import datetime
from zoneinfo import ZoneInfo
zone = ZoneInfo("America/New_York")
first = datetime(2026, 11, 1, 1, 30, tzinfo=zone)
second = first.replace(fold=1)
print(first, first.tzname())
print(second, second.tzname())A ZoneInfo datetime does not automatically reject every nonexistent local time during a spring-forward gap. Validate local input when users enter wall-clock times, or convert through UTC when you need an unambiguous instant.
Arithmetic across a transition
Adding timedelta(days=1) to an aware datetime performs calendar-style, wall-clock arithmetic in the same zone. The elapsed duration can therefore be 23 or 25 hours around a daylight saving transition.
If you need exactly 24 elapsed hours, convert to UTC, add the duration, and convert back:
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
zone = ZoneInfo("America/New_York")
start = datetime(2026, 3, 7, 12, tzinfo=zone)
wall_time = start + timedelta(days=1)
elapsed_time = (start.astimezone(timezone.utc) + timedelta(days=1)).astimezone(zone)
print(wall_time)
print(elapsed_time)Time zone data
ZoneInfo reads IANA time zone data from the operating system or the first-party tzdata package. Minimal containers and some Windows installations may not include system data. Add tzdata as a dependency when your deployment environment cannot guarantee it.
Practical rules
- Store instants as aware UTC datetimes.
- Convert to a user's zone only for display or local scheduling.
- Never compare naive and aware datetimes.
- Use IANA names such as
Europe/Paris, not guessed fixed offsets. - Decide whether each duration means calendar time or elapsed time.
- Preserve
foldor store UTC when a repeated local time matters.
Exercise
Which approach guarantees exactly 24 elapsed hours from an aware datetime across a daylight saving transition?
Show answer
Convert it to UTC, add timedelta(days=1), then convert it back to the desired local zone.