Time zones with zoneinfo
suggest changePython 3.9 added the zoneinfo module (PEP 615). It gives you ZoneInfo, a tzinfo implementation backed by the IANA time zone database (the "Olson" or "tz" database that operating systems use). Before 3.9 you needed a third-party package for named zones like Europe/Warsaw, usually pytz or dateutil. Older articles in this chapter use them: Constructing timezone-aware datetimes and Switching between time zones.
This article covers:
- creating aware datetimes with
ZoneInfoand converting between zones - how arithmetic behaves across daylight saving time (DST) changes
- ambiguous and missing local times, and the
foldattribute - listing zones, the time zone search path and the
tzdatapackage (needed on Windows) datetime.UTC(Python 3.11) and the deprecatedutcnow()- migrating from
pytz
Examples were run with Python 3.13.15 on Windows, with tzdata 2026.5 (IANA 2026e) installed in a virtual environment. Some were also run with Python 3.14.4 on Ubuntu (WSL), which uses the system tz database.
Installing tzdata on Windows
zoneinfo doesn't include the time zone data. It first looks for compiled zone files in the directories listed in zoneinfo.TZPATH, and if a zone isn't there it falls back to the tzdata package from PyPI.
Linux and macOS ship the database in /usr/share/zoneinfo, so it works out of the box. Windows has no such directory, and TZPATH is empty:
import zoneinfo
print(zoneinfo.TZPATH)
$ python tzpath.py # Windows
()
$ python3.14 tzpath.py # Ubuntu
('/usr/share/zoneinfo', '/usr/lib/zoneinfo', '/usr/share/lib/zoneinfo', '/etc/zoneinfo')
Without tzdata every lookup on Windows fails (traceback shortened):
$ python a1.py
Traceback (most recent call last):
...
ModuleNotFoundError: No module named 'tzdata'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "a1.py", line 4, in <module>
warsaw = ZoneInfo("Europe/Warsaw")
...
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Europe/Warsaw'
The fix is to install tzdata into your environment:
$ python -m venv .venv
$ .venv\Scripts\activate
$ pip install tzdata
If your code runs on several platforms, add it to your dependencies. You can limit it to Windows with an environment marker, though many projects install it everywhere. That way containers with no /usr/share/zoneinfo (slim Docker images often lack it) also work:
[project]
dependencies = [
"tzdata; sys_platform == 'win32'",
]
The tzdata package is released whenever IANA publishes a new version of the database, so keep it updated. Governments change their time zone rules several times a year. You can check which version you have:
import tzdata
print(tzdata.IANA_VERSION, tzdata.__version__)
2026e 2026.5
You can change the search path with the PYTHONTZPATH environment variable (an os.pathsep-separated list of absolute paths) or at runtime with zoneinfo.reset_tzpath():
$ PYTHONTZPATH=/opt/zoneinfo:/usr/share/zoneinfo python3.14 tzpath.py
('/opt/zoneinfo', '/usr/share/zoneinfo')
Creating aware datetimes
Pass a ZoneInfo as tzinfo. Unlike with pytz, this is the correct way to use it:
from datetime import datetime
from zoneinfo import ZoneInfo
warsaw = ZoneInfo("Europe/Warsaw")
print(warsaw, repr(warsaw), warsaw.key)
winter = datetime(2026, 1, 15, 12, 0, tzinfo=warsaw)
summer = datetime(2026, 7, 15, 12, 0, tzinfo=warsaw)
for dt in (winter, summer):
print(dt, dt.tzname(), dt.utcoffset(), dt.dst())
Europe/Warsaw zoneinfo.ZoneInfo(key='Europe/Warsaw') Europe/Warsaw
2026-01-15 12:00:00+01:00 CET 1:00:00 0:00:00
2026-07-15 12:00:00+02:00 CEST 2:00:00 1:00:00
The same ZoneInfo object gives different offsets depending on the date. The datetime keeps a reference to the zone and asks it for the offset when needed. The zone doesn't hold a fixed offset.
The key is the IANA name, such as America/New_York or Asia/Kolkata. Abbreviations like CET or EST are not reliable keys: many are ambiguous (IST is used in India, Ireland and Israel), and most don't exist as zone files. Store and accept full IANA names.
ZoneInfo knows the whole history of a zone, not just the current rules. For dates after the last explicit transition in the data file, it uses the rule string at the end of the file, so far-future dates work too:
from datetime import datetime
from zoneinfo import ZoneInfo
warsaw = ZoneInfo("Europe/Warsaw")
for year in (1900, 1944, 1990, 2100):
print(year, datetime(year, 7, 1, tzinfo=warsaw).strftime("%z %Z"))
1900 +0124 WMT
1944 +0200 CEST
1990 +0200 CEST
2100 +0200 CEST
WMT is Warsaw Mean Time, the local solar time used before standard time zones.
Converting between zones
astimezone() converts an aware datetime to another zone. The instant stays the same, only the wall-clock reading changes:
from datetime import datetime
from zoneinfo import ZoneInfo
meeting = datetime(2026, 11, 3, 15, 0, tzinfo=ZoneInfo("Europe/Warsaw"))
for key in ["America/New_York", "Asia/Tokyo", "Australia/Sydney", "UTC"]:
local = meeting.astimezone(ZoneInfo(key))
print(f"{key:18} {local:%Y-%m-%d %H:%M %Z (%z)}")
print(meeting.astimezone().tzinfo)
America/New_York 2026-11-03 09:00 EST (-0500)
Asia/Tokyo 2026-11-03 23:00 JST (+0900)
Australia/Sydney 2026-11-04 01:00 AEDT (+1100)
UTC 2026-11-03 14:00 UTC (+0000)
Central European Standard Time
astimezone() with no argument converts to the system's local time, but the result has a fixed-offset datetime.timezone, not a zone. If you then add a month to it, the offset won't follow DST. To work with the machine's local zone by name, read the key yourself (for example from the TZ environment variable or /etc/localtime on Linux) and pass it to ZoneInfo.
Comparing two aware datetimes in different zones compares the instants, so you can sort or compare datetimes from mixed zones safely. There is one exception, shown in the section about fold below.
Arithmetic across DST changes
Adding a timedelta to an aware datetime works on the wall clock: the date and time fields change, the zone stays the same, and the offset is recalculated for the new local time. Across a DST change this is not the same as adding 24 hours:
from datetime import datetime, timedelta, UTC
from zoneinfo import ZoneInfo
warsaw = ZoneInfo("Europe/Warsaw")
# DST ends in the EU on Sunday 2026-10-25 at 03:00 local time
start = datetime(2026, 10, 24, 12, 0, tzinfo=warsaw)
wall = start + timedelta(days=1)
print("wall clock:", wall, wall.tzname())
exact = (start.astimezone(UTC) + timedelta(days=1)).astimezone(warsaw)
print("24 hours: ", exact, exact.tzname())
print(wall - start)
print(wall.astimezone(UTC) - start.astimezone(UTC))
wall clock: 2026-10-25 12:00:00+01:00 CET
24 hours: 2026-10-25 11:00:00+01:00 CET
1 day, 0:00:00
1 day, 1:00:00
So:
- To mean "same time tomorrow", add a
timedeltato the local datetime. - To mean "exactly 24 hours later", convert to UTC, add, and convert back.
Subtraction follows the same rule. If both datetimes share the same tzinfo object, - ignores the offsets and subtracts wall-clock values, so wall - start above is exactly one day, although 25 hours passed. To get the real elapsed time, convert both to UTC first. When the zones differ, Python converts to UTC by itself.
Wall-clock arithmetic is what you want for recurring events. A daily 09:00 standup in New York stays at 09:00 local time when DST ends, and moves by an hour in UTC:
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
ny = ZoneInfo("America/New_York")
# a daily 09:00 standup keeps its local time across the DST change on 2026-11-01
standup = datetime(2026, 10, 30, 9, 0, tzinfo=ny)
for i in range(4):
day = standup + timedelta(days=i)
print(f"{day:%a %Y-%m-%d %H:%M %Z} = {day.astimezone(ZoneInfo('UTC')):%H:%M} UTC")
Fri 2026-10-30 09:00 EDT = 13:00 UTC
Sat 2026-10-31 09:00 EDT = 13:00 UTC
Sun 2026-11-01 09:00 EST = 14:00 UTC
Mon 2026-11-02 09:00 EST = 14:00 UTC
This also suggests how to store times. Store past events (log lines, payments) as UTC. For future events that people schedule in local time, store the local datetime and the zone key. If the zone's rules change before the event, converting at the last moment gives the right UTC time, while a UTC value computed in advance would be off by the size of the change.
Ambiguous times and fold
When DST ends, clocks go back and an hour of local time happens twice. In Warsaw on 2026-10-25, clocks go from 03:00 CEST back to 02:00 CET, so 02:30 happens twice. A naive date and time can't tell the two apart. PEP 495 added the fold attribute: fold=0 (the default) means the first occurrence and fold=1 means the second:
from datetime import datetime, UTC
from zoneinfo import ZoneInfo
warsaw = ZoneInfo("Europe/Warsaw")
# 02:30 happens twice on 2026-10-25: clocks go from 03:00 CEST back to 02:00 CET
first = datetime(2026, 10, 25, 2, 30, tzinfo=warsaw)
second = first.replace(fold=1)
for dt in (first, second):
print(dt, dt.fold, dt.tzname(), dt.astimezone(UTC))
print(first == second)
print(second - first)
print(second.astimezone(UTC) - first.astimezone(UTC))
2026-10-25 02:30:00+02:00 0 CEST 2026-10-25 00:30:00+00:00
2026-10-25 02:30:00+01:00 1 CET 2026-10-25 01:30:00+00:00
True
0:00:00
1:00:00
ZoneInfo uses fold to choose the offset, so the two values convert to UTC instants an hour apart. Comparisons and subtraction within the same zone still ignore fold and look only at the wall clock: first == second is True. This is the same wall-clock rule as above.
Converting from UTC sets fold for you, so a sequence of UTC instants maps to correct local times:
from datetime import datetime, timedelta, UTC
from zoneinfo import ZoneInfo
warsaw = ZoneInfo("Europe/Warsaw")
t = datetime(2026, 10, 25, 0, 0, tzinfo=UTC)
for i in range(4):
local = (t + timedelta(minutes=30 * i)).astimezone(warsaw)
print(f"{local} fold={local.fold} {local.tzname()}")
2026-10-25 02:00:00+02:00 fold=0 CEST
2026-10-25 02:30:00+02:00 fold=0 CEST
2026-10-25 02:00:00+01:00 fold=1 CET
2026-10-25 02:30:00+01:00 fold=1 CET
The exception mentioned earlier: when Python compares datetimes from different zones, a value whose offset depends on fold (any time in an ambiguous or missing period, with either fold value) never compares equal to a datetime in another zone, even when both are the same instant. PEP 495 chose this so that == stays consistent with hashing:
from datetime import datetime, UTC
from zoneinfo import ZoneInfo
warsaw = ZoneInfo("Europe/Warsaw")
for fold in (0, 1):
local = datetime(2026, 10, 25, 2, 30, fold=fold, tzinfo=warsaw)
utc = local.astimezone(UTC)
print(local, utc, local == utc, local.astimezone(UTC) == utc, local.timestamp() == utc.timestamp())
normal = datetime(2026, 10, 25, 4, 30, tzinfo=warsaw)
print(normal, normal == normal.astimezone(UTC))
2026-10-25 02:30:00+02:00 2026-10-25 00:30:00+00:00 False True True
2026-10-25 02:30:00+01:00 2026-10-25 01:30:00+00:00 False True True
2026-10-25 04:30:00+01:00 True
If you need reliable equality across zones, convert both sides to UTC (or compare timestamps) first. Only == and != are affected. < and > compare the instants as usual.
Missing times
When DST starts, clocks jump forward and an hour of local time never happens. In Warsaw on 2026-03-29, clocks go from 02:00 CET straight to 03:00 CEST. ZoneInfo doesn't raise an error for 02:30. Following PEP 495, fold=0 uses the offset from before the jump and fold=1 the offset after it, and converting through UTC gives a real time:
from datetime import datetime, UTC
from zoneinfo import ZoneInfo
warsaw = ZoneInfo("Europe/Warsaw")
# 02:30 never happens on 2026-03-29: clocks jump from 02:00 CET to 03:00 CEST
missing = datetime(2026, 3, 29, 2, 30, tzinfo=warsaw)
print(missing, missing.tzname())
print(missing.astimezone(UTC).astimezone(warsaw))
late = missing.replace(fold=1)
print(late, late.astimezone(UTC).astimezone(warsaw))
2026-03-29 02:30:00+01:00 CET
2026-03-29 03:30:00+02:00
2026-03-29 02:30:00+02:00 2026-03-29 01:30:00+01:00
With fold=0 (the default) a missing time moves forward by the length of the gap, which is usually what a calendar app wants.
When the input comes from a user, you may prefer to reject missing and ambiguous times. zoneinfo has no strict mode, but a helper is short. If the offsets for fold=0 and fold=1 differ, the time is in a gap or a fold. A UTC round trip tells which one:
from datetime import datetime, UTC
from zoneinfo import ZoneInfo
def localize_strict(naive, tz):
"""Attach tz to a naive datetime, refusing missing and ambiguous times."""
early = naive.replace(tzinfo=tz, fold=0)
late = naive.replace(tzinfo=tz, fold=1)
if early.utcoffset() == late.utcoffset():
return early
roundtrip = early.astimezone(UTC).astimezone(tz).replace(tzinfo=None)
if roundtrip != naive:
raise ValueError(f"{naive} does not exist in {tz}")
raise ValueError(f"{naive} is ambiguous in {tz}")
warsaw = ZoneInfo("Europe/Warsaw")
for naive in [datetime(2026, 7, 15, 12, 0), datetime(2026, 10, 25, 2, 30), datetime(2026, 3, 29, 2, 30)]:
try:
print(localize_strict(naive, warsaw))
except ValueError as e:
print("error:", e)
2026-07-15 12:00:00+02:00
error: 2026-10-25 02:30:00 is ambiguous in Europe/Warsaw
error: 2026-03-29 02:30:00 does not exist in Europe/Warsaw
DST isn't the only cause. Zones also change their base offset. Samoa moved across the international date line at the end of 2011 and skipped December 30 entirely, and ZoneInfo knows that:
from datetime import datetime, timedelta, UTC
from zoneinfo import ZoneInfo
apia = ZoneInfo("Pacific/Apia")
t = datetime(2011, 12, 30, 9, 0, tzinfo=UTC)
for hours in (0, 1, 2):
local = (t + timedelta(hours=hours)).astimezone(apia)
print(f"{local:%Y-%m-%d %H:%M %z}")
2011-12-29 23:00 -1000
2011-12-31 00:00 +1400
2011-12-31 01:00 +1400
Listing zones
zoneinfo.available_timezones() returns a set of every valid key it can find in TZPATH and in tzdata. It scans the disk, so call it once and keep the result, for example to validate user input or fill a drop-down:
import zoneinfo
zones = zoneinfo.available_timezones()
print(len(zones))
print(sorted(z for z in zones if z.startswith("Europe/W")))
print("US/Eastern" in zones, "EST5EDT" in zones, "CET" in zones)
print("UTC" in zones, "Etc/UTC" in zones, "localtime" in zones)
$ python zones.py # Windows, tzdata 2026.5
598
['Europe/Warsaw']
True True True
True True False
$ python3.14 zones.py # Ubuntu 26.04, system tzdata 2026c
486
['Europe/Warsaw']
False False False
True True True
The result depends on the machine. Ubuntu moved old names such as US/Eastern and CET into a separate tzdata-legacy package, and its /usr/share/zoneinfo also contains a localtime file that looks like a key. The tzdata package includes the legacy names. Code that depends on old names works on one machine and fails on another, so prefer canonical Area/City keys.
Grouping by region:
from collections import Counter
import zoneinfo
regions = Counter(z.split("/")[0] for z in zoneinfo.available_timezones() if "/" in z)
for region, n in regions.most_common(6):
print(f"{region:12} {n}")
America 169
Asia 99
Europe 64
Africa 54
Pacific 44
Etc 35
Caching, errors and pickling
ZoneInfo(key) caches instances, so calling it repeatedly with the same key returns the same object. That's important: same-zone arithmetic and comparison check whether the tzinfo objects are identical, not equal.
import pickle
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
a = ZoneInfo("Europe/Warsaw")
b = ZoneInfo("Europe/Warsaw")
print(a is b)
fresh = ZoneInfo.no_cache("Europe/Warsaw")
print(fresh is a, fresh == a)
print(pickle.loads(pickle.dumps(a)) is a)
for key in ["Europe/Warsww", "europe/warsaw", "../etc/passwd"]:
try:
ZoneInfo(key)
except ZoneInfoNotFoundError as e:
print("not found:", e)
except ValueError as e:
print("bad key:", e)
print(issubclass(ZoneInfoNotFoundError, KeyError))
True
False False
True
not found: 'No time zone found with key Europe/Warsww'
not found: 'No time zone found with key europe/warsaw'
bad key: ZoneInfo keys must refer to subdirectories of TZPATH, got: ../etc/passwd
True
Notes:
ZoneInfo.no_cache(key)bypasses the cache and returns a new object.ZoneInfoobjects compare by identity, so it isn't equal to the cached one.ZoneInfo.clear_cache()empties the cache, for example after updating the data files while the program runs.- Pickling stores only the key, and unpickling calls
ZoneInfo(key)again. You get the cached instance, and the receiving side uses its own copy of the database. ZoneInfoNotFoundErroris a subclass ofKeyError. Keys are case-sensitive, and keys that try to escape the search path raiseValueError.
ZoneInfo.from_file() builds a zone from a binary TZif file object. Such a zone has no key in the cache, so it can't be pickled:
import pickle
from datetime import datetime
from zoneinfo import ZoneInfo
with open("/usr/share/zoneinfo/Europe/Warsaw", "rb") as f:
tz = ZoneInfo.from_file(f, key="Warsaw (system copy)")
print(tz, datetime(2026, 7, 1, tzinfo=tz).tzname())
try:
pickle.dumps(tz)
except pickle.PicklingError as e:
print(e)
Warsaw (system copy) CEST
Cannot pickle a ZoneInfo file from a file stream.
datetime.UTC and timezone-aware "now"
For UTC you don't need zoneinfo at all. datetime.timezone.utc has existed since Python 3.2, and Python 3.11 added the shorter alias datetime.UTC for the same object:
import datetime as dt
print(dt.UTC is dt.timezone.utc)
print(dt.datetime.now(dt.UTC))
print(dt.datetime.now(dt.UTC).tzinfo, repr(dt.UTC))
True
2026-10-17 23:03:42.212644+00:00
UTC datetime.timezone.utc
On Python 3.10 and older this fails with AttributeError: module 'datetime' has no attribute 'UTC'. Use timezone.utc if you support those versions. ZoneInfo("UTC") also works, but it is a different object, it needs the tz database, and it isn't faster.
datetime.utcnow() and datetime.utcfromtimestamp() return naive datetimes that hold UTC values. Since many functions treat naive datetimes as local time, this was a common source of bugs. Both are deprecated since Python 3.12:
import datetime as dt
naive = dt.datetime.utcnow()
print(naive, naive.tzinfo)
print(dt.datetime.fromtimestamp(0, dt.UTC))
f2.py:3: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
naive = dt.datetime.utcnow()
2026-10-17 23:03:42.456862 None
1970-01-01 00:00:00+00:00
Replace them with datetime.now(UTC) and datetime.fromtimestamp(ts, UTC).
Migrating from pytz
pytz was written before PEP 495. Its zones can't work out the offset when a datetime is created, so every pytz zone has a fixed offset attached and you must fix it up with localize() and normalize(). Passing a pytz zone as tzinfo= gives a silently wrong result, the zone's first offset from the 19th century:
from datetime import datetime, timedelta
import pytz
warsaw = pytz.timezone("Europe/Warsaw")
wrong = datetime(2026, 7, 15, 12, 0, tzinfo=warsaw)
print("tzinfo= ", wrong, wrong.tzname())
right = warsaw.localize(datetime(2026, 7, 15, 12, 0))
print("localize:", right, right.tzname())
later = right + timedelta(days=120)
print("added: ", later, later.tzname())
print("normalize", warsaw.normalize(later), warsaw.normalize(later).tzname())
tzinfo= 2026-07-15 12:00:00+01:24 LMT
localize: 2026-07-15 12:00:00+02:00 CEST
added: 2026-11-12 12:00:00+02:00 CEST
normalize 2026-11-12 11:00:00+01:00 CET
With zoneinfo the obvious code is correct, and the offset follows the date after arithmetic:
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
warsaw = ZoneInfo("Europe/Warsaw")
dt = datetime(2026, 7, 15, 12, 0, tzinfo=warsaw)
print("tzinfo=", dt, dt.tzname())
later = dt + timedelta(days=120)
print("added: ", later, later.tzname())
tzinfo= 2026-07-15 12:00:00+02:00 CEST
added: 2026-11-12 12:00:00+01:00 CET
Note that pytz and zoneinfo also give different results for the same addition. pytz without normalize() keeps the old offset and does absolute-time arithmetic (normalize() then shows 11:00), while zoneinfo keeps 12:00 on the wall clock. Review arithmetic around DST changes when you migrate.
pytz chose between the two readings of an ambiguous time with is_dst:
from datetime import datetime
import pytz
warsaw = pytz.timezone("Europe/Warsaw")
naive = datetime(2026, 10, 25, 2, 30)
print(warsaw.localize(naive, is_dst=True))
print(warsaw.localize(naive, is_dst=False))
try:
warsaw.localize(naive, is_dst=None)
except pytz.AmbiguousTimeError as e:
print("AmbiguousTimeError:", e)
2026-10-25 02:30:00+02:00
2026-10-25 02:30:00+01:00
AmbiguousTimeError: 2026-10-25 02:30:00
Translation table:
| pytz | zoneinfo |
|---|---|
pytz.timezone("Europe/Warsaw") |
ZoneInfo("Europe/Warsaw") |
tz.localize(naive) |
naive.replace(tzinfo=tz) |
tz.localize(naive, is_dst=True) |
naive.replace(tzinfo=tz, fold=0) |
tz.localize(naive, is_dst=False) |
naive.replace(tzinfo=tz, fold=1) |
tz.localize(naive, is_dst=None) |
a helper like localize_strict() above |
tz.normalize(dt) |
not needed (the offset follows the date) |
dt.astimezone(tz) |
dt.astimezone(tz) (unchanged) |
pytz.utc / pytz.UTC |
datetime.UTC (3.11+) or timezone.utc |
pytz.all_timezones |
zoneinfo.available_timezones() |
pytz.UnknownTimeZoneError |
zoneinfo.ZoneInfoNotFoundError |
The is_dst mapping holds for normal DST transitions in the northern hemisphere, where the first occurrence is the summer time. Strictly, fold=0 means "earlier" and fold=1 means "later", which isn't always the DST reading.
For code that has to support both during a transition, the pytz-deprecation-shim package provides pytz-style localize() and normalize() on top of zoneinfo. dateutil.tz.gettz() zones also support fold and can be replaced with ZoneInfo without other changes.
Summary
| Task | Code |
|---|---|
| a named zone | ZoneInfo("Europe/Warsaw") (3.9+) |
| UTC | datetime.UTC (3.11+) or timezone.utc |
| current time in a zone | datetime.now(ZoneInfo(key)) |
| attach a zone to a naive datetime | naive.replace(tzinfo=tz) |
| convert to another zone | dt.astimezone(tz) |
| same wall-clock time tomorrow | dt + timedelta(days=1) |
| exactly 24 hours later | (dt.astimezone(UTC) + timedelta(hours=24)).astimezone(tz) |
| second occurrence of an ambiguous time | dt.replace(fold=1) |
| list zones | zoneinfo.available_timezones() |
| data on Windows | pip install tzdata |
Things to remember:
- Install
tzdataon Windows and in minimal containers, and keep it updated. - Use IANA keys, not abbreviations, and prefer canonical names over legacy ones like
US/Eastern. - Arithmetic and subtraction within one zone use wall-clock time. Go through UTC for elapsed time.
foldpicks between the two readings of an ambiguous time. Missing times don't raise errors, so validate user input yourself if needed.- Store past events in UTC. Store future local events as local time plus zone key.