Sub topic 11
Where time zone data comes from, and the tzdata package
This chapter assumes you can use ZoneInfo to attach a zone to a datetime and convert it with astimezone, and that you know what an exception is. You should also know that Python 3.9 or later is required for zoneinfo. Here you will learn where the rules behind ZoneInfo("America/New_York") are stored, how Python finds them, and what to do when it can't.
Why Python needs outside data
A time zone is a set of political decisions: a UTC offset, the dates daylight saving starts and ends, and the history of past changes. Governments change these decisions, sometimes with only a few weeks of notice. Mexico, for example, abolished daylight saving time in October 2022.
Python's standard library can't contain rules that keep changing. Instead, zoneinfo reads a shared database and does not hard-code any rule.
The IANA time zone database
The IANA time zone database is also called tz, tzdata, or the Olson database. It is a community-maintained collection of rules and history for every region, and IANA hosts it. Each release has a version name such as 2025b: the year, then a letter for the release within that year. Releases appear several times a year, whenever a government changes a rule.
The source files are plain text. They are compiled into binary TZif files, one per zone, organized in directories that match the zone key:
America/New_Yorkis a file namedNew_Yorkinside a directory namedAmerica.UTCis a file at the top level.
A TZif file holds the list of past transitions (offset changes) and a rule for future ones. This is why ZoneInfo can give a correct offset for 1975 and for 2040 from the same file.
Where ZoneInfo looks for data
When you call ZoneInfo("Europe/Paris"), Python searches in a fixed order:
- Each directory in
zoneinfo.TZPATH, in order, looking for a file at that key. - The
tzdatapackage from PyPI, if it is installed. - If both fail, it raises
ZoneInfoNotFoundError.
The system directories come first, so the tzdata package is a fallback. If your operating system and the tzdata package hold different releases, Python uses the operating system's copy.
Inspecting the search path
import zoneinfo
print(zoneinfo.TZPATH)On Linux the output is usually a tuple like ('/usr/share/zoneinfo', '/usr/lib/zoneinfo', '/usr/share/lib/zoneinfo', '/etc/zoneinfo'). On Windows it is an empty tuple, because Windows ships no compatible database.
You can change the search path in two ways:
- Set the
PYTHONTZPATHenvironment variable to directories separated byos.pathsep(:on Linux and macOS,;on Windows). - Call
zoneinfo.reset_tzpath(to=[...])at runtime.
Both accept only absolute paths. A relative path raises ValueError. If PYTHONTZPATH is set to an empty string, Python skips the system directories and relies on the tzdata package only. That is useful when you want every machine to use the exact same data.
What differs by platform
| Platform | System database | What to do |
|---|---|---|
| Linux | Usually in `/usr/share/zoneinfo`, from the OS `tzdata` package | Nothing, unless the image is minimal |
| macOS | `/usr/share/zoneinfo` | Nothing |
| Windows | None usable by Python | Install `tzdata` from PyPI |
| Minimal containers | Often missing | Install the OS `tzdata` package or the PyPI one |
The error you see in these cases looks like this:
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key America/New_York'ZoneInfoNotFoundError is a subclass of KeyError. Code that catches KeyError will therefore also catch it, so be specific about what you catch.
The tzdata package
The tzdata package on PyPI contains the same database in a form that pip can install. It is maintained by the Python core developers and released to follow each IANA release. Its version number matches the IANA name, so 2025.2 corresponds to IANA release 2025b. Install it with:
pip install tzdataIn a project that supports several platforms, declare it as a dependency. A line in requirements.txt can limit it to Windows, where it is required:
tzdata; sys_platform == "win32"Many projects install it everywhere instead. This gives identical behavior on every machine, at the cost of a package of about one megabyte.
Checking which data you have
You can check whether the package is present, and which release it holds:
from importlib import metadata
try:
print("tzdata package:", metadata.version("tzdata"))
except metadata.PackageNotFoundError:
print("tzdata package is not installed")This tells you only about the PyPI package. If the system database exists, Python may be using that one instead. To see what Python can find from all sources, use available_timezones():
import zoneinfo
zones = zoneinfo.available_timezones()
print(len(zones) > 400)
print("Asia/Tokyo" in zones)Both lines print True on a machine with working data. On a machine with no data at all, the set is empty.
Handling missing data in your program
Missing data is an environment problem, not a bug in the user's input. It is worth failing with a clear message. Distinguish it from a typo in a zone name, which gives the same exception:
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezones
def load_zone(key):
try:
return ZoneInfo(key)
except ZoneInfoNotFoundError:
if not available_timezones():
raise SystemExit("No time zone data found. Run: pip install tzdata")
raise SystemExit(f"Unknown time zone: {key!r}")
print(load_zone("Europe/Paris"))On a working machine this prints zoneinfo.ZoneInfo(key='Europe/Paris'). If available_timezones() returns an empty set, the environment has no data. If it returns zones but your key isn't among them, the key is wrong.
Keys are validated
ZoneInfo treats the key as a relative path inside the database, so it rejects keys that could escape it:
from zoneinfo import ZoneInfo
for bad in ["../etc/passwd", "/etc/localtime"]:
try:
ZoneInfo(bad)
except ValueError as e:
print(type(e).__name__, "for", bad)Both keys raise ValueError, so the output is two lines starting with ValueError. This matters if you accept zone names from users: a bad name gives either ValueError (malformed) or ZoneInfoNotFoundError (well-formed but unknown). Catch both.
Caching and stale data
ZoneInfo caches objects by key. Two calls with the same key return the very same object, which saves reading the file again and makes comparisons cheap:
from zoneinfo import ZoneInfo
a = ZoneInfo("Europe/London")
b = ZoneInfo("Europe/London")
print(a is b)
ZoneInfo.clear_cache()
c = ZoneInfo("Europe/London")
print(a is c)
d = ZoneInfo.no_cache("Europe/London")
print(c is d)This prints True, False, False. clear_cache() empties the cache, so the next call reads the file again. no_cache() always reads a fresh copy and doesn't store it.
The cache has a practical consequence for long-running programs. A server that started before a data update keeps the old rules in memory, even after the operating system or the tzdata package is upgraded. Restarting the process is the reliable fix. clear_cache() also works, but any datetime that already holds an old ZoneInfo object keeps using the old rules.
When a data update changes your results
A new release changes the answer only for times that are affected by the new rule. Two kinds of stored values behave differently:
- A past event stored in UTC. The instant is fixed, so an update does not change it. At most, the local time shown for it may change if the history was corrected.
- A future event stored as local time plus zone name. The instant depends on the rules, so an update can change it. If a government moves a daylight saving date, "09:00 in that zone" now means a different UTC moment.
This is why a calendar app should store a future appointment as the local time and the zone key, for example 2027-03-20 09:00 and America/Santiago. If it stored UTC only, a rule change would leave the meeting at the wrong local hour. The earlier chapters' advice to store UTC applies to events that have already happened, or that are defined as exact instants, such as log entries.
Practical rules for this chapter
- On Windows, and in minimal containers, add
tzdatato your dependencies. - Prefer one data source across your machines. Setting
PYTHONTZPATH=""forces thetzdatapackage everywhere. - Catch
ZoneInfoNotFoundErrorandValueErrorwhere user input becomes a zone key. - Keep
tzdataup to date, and restart long-running processes after an update. - Store future local appointments as local time plus zone key, not as UTC alone.
Exercise
A script works on your Linux laptop, but a colleague on Windows gets ZoneInfoNotFoundError: 'No time zone found with key Europe/Paris' from ZoneInfo("Europe/Paris"). The key is spelled correctly. What is the cause, what is the fix, and how can the script tell this case apart from a misspelled key?
Show answer
Windows has no time zone database in a location Python searches, so zoneinfo.TZPATH is empty and the lookup falls through to the tzdata package, which is not installed. The fix is pip install tzdata, and adding tzdata; sys_platform == "win32" to the project's requirements. To tell the cases apart, call zoneinfo.available_timezones(). An empty set means no data exists at all, so the environment is the problem. A non-empty set that lacks the key means the key itself is wrong.
Exercise
Your service started last week and caches ZoneInfo("America/Sao_Paulo"). Today you upgrade the tzdata package to a release that changes that zone's rules. New datetimes created in the service still show the old offset for the changed dates. Why, and what are two ways to fix it?
Show answer
ZoneInfo caches the object by key, so the process keeps the rules it loaded before the upgrade. The first fix is to restart the process, which is the most reliable. The second is to call ZoneInfo.clear_cache() so later ZoneInfo(...) calls read the new data. Datetimes that already hold the old object still use the old rules, so they need to be rebuilt. Also remember that if the operating system's database is present, Python reads that copy first, so upgrading the PyPI package changes nothing until the system database is missing or older data is removed from the path.