A zone-aware datetime combines a local clock reading with timezone rules; fold distinguishes repeated local times during a backward clock transition.
Python zoneinfo and fold: two instants can share one clock label
Operation contract
The fixture converts two known UTC instants into America/New_York. Both display 01:30 on the transition date, but their offsets and fold values differ. Starting from UTC avoids guessing which instant an ambiguous user-entered clock reading intended. Appointment entry needs its own reject-or-select policy; conversion cannot infer one.
Failure and ownership boundary
ZoneInfo uses installed IANA timezone data, which may differ across deployments. The source kit pins tzdata for a portable fallback, but a system timezone database can take precedence. Arithmetic on local datetimes and equality with the same zone object also require care around folds; compare UTC instants for elapsed-time decisions. Python datetime: require an offset before comparing timestamps is the simpler wire format.
Working program
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
zone = ZoneInfo("America/New_York")
for hour in (5, 6):
instant = datetime(2024, 11, 3, hour, 30, tzinfo=timezone.utc)
local = instant.astimezone(zone)
print(local.isoformat(), "fold=" + str(local.fold))Output
2024-11-03T01:30:00-04:00 fold=0
2024-11-03T01:30:00-05:00 fold=1Costs and limits
Zone rules are loaded and cached by the runtime. This fixture converts two instants; it does not measure timezone lookup cost or claim an elapsed-hour calculation from local labels.
Common Mistakes
- A timezone name does not resolve an ambiguous typed clock reading automatically.
- Store the timezone database/version policy when future scheduling depends on it.
Connected lessons
Python datetime: require an offset before comparing timestamps, Python strings and bytes: reject decoding errors before parsing records.
Follow the ownership and update boundary
Python ZoneInfo: classify unique, repeated and missing local times.
