Time zones with zoneinfo
- Version
- 3.14
- Since
- 3.9
- Review
- Draft
Summary#
ZoneInfo supplies the offset rules for an IANA time zone. Convert an aware datetime with astimezone to see the same instant in a different zone.
Syntax#
zone = ZoneInfo("Europe/Berlin")
local = aware_datetime.astimezone(zone)
Example#
Two UTC instants map to the same wall-clock time when the clocks in Berlin go back. The offset and fold distinguish the two occurrences.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
berlin = ZoneInfo("Europe/Berlin")
for hour in (0, 1):
instant = datetime(2022, 10, 30, hour, 15, tzinfo=timezone.utc)
local = instant.astimezone(berlin)
print(local.isoformat(), "fold", local.fold)
Expected output#
2022-10-30T02:15:00+02:00 fold 0
2022-10-30T02:15:00+01:00 fold 1
Common mistakes#
replace(tzinfo=zone) attaches a zone without shifting the clock fields. Use astimezone to preserve the instant. If the system lacks IANA time zone data, install the first-party tzdata package. If neither source supplies the requested zone, ZoneInfo raises ZoneInfoNotFoundError.
Version applicability#
ZoneInfo requires Python 3.9 or later, as does the full example. The fold attribute was added in Python 3.6.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0