Sub topic 7
Real-world time zones with ZoneInfo
This chapter assumes you know naive and aware datetimes, UTC, and fixed-offset zones such as timezone.utc from the earlier chapters. It also assumes Python 3.9 or later, where the zoneinfo module is in the standard library.
Why fixed offsets are not enough
A timezone(timedelta(hours=-5)) object always means "five hours behind UTC". That is correct for New York in winter and wrong in summer, when New York is four hours behind. A real zone is a history of rules: which offset applies, when daylight saving time (DST) starts and ends, and how governments changed those rules over the years.
The IANA time zone database (also called tz, tzdata, or the Olson database) records those rules. zoneinfo.ZoneInfo is a tzinfo subclass that reads that database and answers one question for any datetime: what is the UTC offset at this moment in this place?
Creating a ZoneInfo object
You build a ZoneInfo from a key, which is an IANA name of the form Area/Location, such as America/New_York, Europe/Berlin, or Asia/Tokyo. You attach it to a datetime with the tzinfo argument.
from datetime import datetime
from zoneinfo import ZoneInfo
ny = ZoneInfo("America/New_York")
winter = datetime(2026, 1, 15, 9, 0, tzinfo=ny)
summer = datetime(2026, 7, 15, 9, 0, tzinfo=ny)
for dt in (winter, summer):
hours = dt.utcoffset().total_seconds() / 3600
print(dt.isoformat(), dt.tzname(), hours, dt.dst())This prints:
2026-01-15T09:00:00-05:00 EST -5.0 0:00:00
2026-07-15T09:00:00-04:00 EDT -4.0 1:00:00The same zone object produced two different offsets. Each datetime asks the zone for its offset when you call utcoffset(), tzname(), or dst(). The offset is not stored on the datetime.
| Method or attribute | Returns | Example for the summer datetime |
|---|---|---|
| `utcoffset()` | A `timedelta` ahead of or behind UTC | `-1 day, 20:00:00` (four hours behind) |
| `tzname()` | The abbreviation in use at that moment | `EDT` |
| `dst()` | The DST part of the offset, as a `timedelta` | `1:00:00` |
| `tzinfo.key` | The IANA name the zone was built from | `America/New_York` |
Passing tzinfo=ny directly to the constructor is the correct way to attach a ZoneInfo. If you used the older pytz library, you may remember a localize() step. ZoneInfo does not need it, and the constructor argument gives the right result.
Using the current time
datetime.now() accepts a zone directly and returns an aware datetime in that zone:
from datetime import datetime
from zoneinfo import ZoneInfo
now_london = datetime.now(ZoneInfo("Europe/London"))
print(now_london.tzname())This prints GMT in winter and BST in summer.
Choosing and validating names
Always use region-based IANA names for people and places. Abbreviations such as CST are ambiguous: they can mean US Central Standard Time, China Standard Time, or Cuba Standard Time. They also say nothing about DST. A name like America/Chicago carries the whole rule history for that place.
Some names are aliases kept for compatibility, such as US/Eastern for America/New_York. They work, but prefer the Area/Location names so your stored values are consistent.
You can list every name your system can find:
import zoneinfo
names = zoneinfo.available_timezones()
print("America/New_York" in names)
print(len(names) > 400)Both lines print True. available_timezones() returns a set of strings. It is useful for building a drop-down list or validating input, but it reflects whatever data the current machine has.
Handling bad names
A misspelled or missing key raises ZoneInfoNotFoundError, a subclass of KeyError. A key that is not a valid relative path, such as one that tries to climb out of the data directory with .., raises ValueError. When a name comes from user input or a config file, translate the error into something meaningful:
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
def load_zone(name):
try:
return ZoneInfo(name)
except ZoneInfoNotFoundError:
raise ValueError(f"Unknown time zone: {name!r}") from None
print(load_zone("Europe/Berlin").key)
try:
load_zone("Europe/Berln")
except ValueError as e:
print(e)This prints Europe/Berlin and then Unknown time zone: 'Europe/Berln'.
A ZoneInfoNotFoundError for a name you know is correct usually means the machine has no time zone data at all. That happens on Windows and in minimal containers. The chapter on tzdata covers the fix.
Replacing a zone versus converting to one
Two operations look similar and do opposite things. replace(tzinfo=...) keeps the clock fields and swaps the label, which changes the instant in time. astimezone(...) keeps the instant and recomputes the clock fields.
from datetime import datetime
from zoneinfo import ZoneInfo
ny = ZoneInfo("America/New_York")
tokyo = ZoneInfo("Asia/Tokyo")
dt = datetime(2026, 11, 26, 9, 0, tzinfo=ny)
relabelled = dt.replace(tzinfo=tokyo)
converted = dt.astimezone(tokyo)
print(relabelled)
print(converted)
print(relabelled == converted)The output is:
2026-11-26 09:00:00+09:00
2026-11-26 23:00:00+09:00
FalseThe relabelled value claims a meeting at 09:00 in Tokyo, which is a different moment from 09:00 in New York. Use replace(tzinfo=...) only when you know a naive datetime was in a given zone all along. For example, a form field that holds local time and a separate zone name. Use astimezone to move an aware datetime between zones. The next chapter covers conversion in detail.
Zone objects are cached
ZoneInfo("Europe/Paris") does not parse the data file each time. The class keeps a cache, so repeated calls with the same key return the same object:
from zoneinfo import ZoneInfo
a = ZoneInfo("Europe/Paris")
b = ZoneInfo("Europe/Paris")
c = ZoneInfo.no_cache("Europe/Paris")
print(a is b)
print(a is c)
print(a.key)This prints True, False, and Europe/Paris.
This has a practical consequence for comparisons. Python decides how to compare two aware datetimes by checking whether they share the same tzinfo object. Because of the cache, two datetimes built with ZoneInfo("Europe/Paris") usually do share it. Use ZoneInfo.no_cache() only in tests or other special cases, and call ZoneInfo.clear_cache() if you need the cache emptied, for example after updating data files at runtime.
The same-zone comparison gotcha
When two aware datetimes share one tzinfo object, Python compares and subtracts their local clock fields and ignores the offsets. This is usually harmless, but it gives surprising answers inside a DST repeat, when one local time occurs twice:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
ny = ZoneInfo("America/New_York")
first = datetime(2026, 11, 1, 1, 30, tzinfo=ny)
second = first.replace(fold=1)
print(first == second)
print(second - first)
print(first.astimezone(timezone.utc))
print(second.astimezone(timezone.utc))The output is:
True
0:00:00
2026-11-01 05:30:00+00:00
2026-11-01 06:30:00+00:00The two values are one real hour apart, yet within the same zone they compare equal and subtract to zero. The fold attribute picks which of the two occurrences you mean, and the DST chapter explains it fully. For now, remember the safe habit: convert to UTC before you compare or subtract datetimes that might fall near a DST change.
Zone data changes over time
Governments change time zone rules, sometimes with only weeks of notice. The IANA database is updated several times a year to follow them. Two things follow from this.
First, a ZoneInfo answers using the data installed on the machine at the time of the call. If rules change, the same future datetime can report a different offset after an update.
Second, a future event should be stored as local clock time plus a zone name, not as a UTC value you computed today. Suppose you book a dentist appointment for 09:00 in Europe/Berlin next March. If Germany changes its DST rules before then, 09:00 local is still the intent, but the UTC instant is different. Store 2027-03-20T09:00 and Europe/Berlin, and compute the UTC instant when you need it. Past events are different: their rules are settled, so a UTC timestamp is safe.
Zone keys are also what you should persist. Never store an offset or an abbreviation as the zone identity, because neither lets you recompute later:
from datetime import datetime
from zoneinfo import ZoneInfo
appointment = datetime(2027, 3, 20, 9, 0, tzinfo=ZoneInfo("Europe/Berlin"))
record = {
"local": appointment.replace(tzinfo=None).isoformat(),
"zone": appointment.tzinfo.key,
}
print(record)
restored = datetime.fromisoformat(record["local"]).replace(
tzinfo=ZoneInfo(record["zone"])
)
print(restored == appointment)This prints {'local': '2027-03-20T09:00:00', 'zone': 'Europe/Berlin'} and then True. Here replace(tzinfo=...) is the right tool: the stored local time was always in that zone, so you are restoring the label, not changing the instant.
Common mistakes
- Using abbreviations as keys.
ZoneInfo("CST")may exist as a legacy entry but does not follow DST. UseAmerica/Chicago. - Confusing
replacewithastimezone. Relabelling shifts the instant. Converting preserves it. - Assuming one offset per zone. A zone has many offsets across its history. Ask the datetime, never the zone name.
- Comparing within one zone near a DST change. Convert to UTC first.
- Catching
KeyErrortoo broadly.ZoneInfoNotFoundErroris aKeyError, but catch the specific exception so you do not hide unrelated lookup bugs. - Trusting
available_timezones()as a list of valid inputs everywhere. It lists only what the current machine has.
Exercises
Exercise
A form gives you the naive datetime 2026-07-15 18:30 and the zone name "Australia/Sydney". Write the expression that makes it an aware datetime in that zone, and say why you would use replace(tzinfo=...) or the tzinfo constructor argument instead of astimezone here.
Show answer
Use datetime(2026, 7, 15, 18, 30, tzinfo=ZoneInfo("Australia/Sydney")), or datetime.fromisoformat("2026-07-15T18:30").replace(tzinfo=ZoneInfo("Australia/Sydney")). The naive value was already local time in Sydney, so you are only attaching the missing label. astimezone would treat a naive value as system local time and convert from that, which gives the wrong instant unless the machine happens to be in Sydney.
Exercise
What do these lines print, and why? ny = ZoneInfo("America/New_York"); a = datetime(2026, 7, 15, 9, 0, tzinfo=ny); b = a.astimezone(ZoneInfo("UTC")); print(a == b); print(a.utcoffset() == b.utcoffset())
Show answer
The first line prints True and the second prints False. The two datetimes use different tzinfo objects, so Python compares the real instants, and 09:00 EDT equals 13:00 UTC. Their offsets are different (-4 hours and 0), so the second comparison is False.
Exercise
You are saving a webinar scheduled for 19:00 on a date eight months away in "Europe/Madrid". Should you store a UTC timestamp or local time plus a zone key? Give the reason.
Show answer
Store the local time (2026-style value such as 19:00 on that date) plus the key "Europe/Madrid". The intent is 19:00 in Madrid. If the rules for DST change before the date, the correct UTC instant changes with them, and a UTC value computed today would then be wrong. Compute the UTC instant from the stored local time and zone when you need it.