Sub topic 12
Time zone backends: zoneinfo, pytz and dateutil
This chapter assumes you can already use tz_localize and tz_convert, and that you know what an IANA zone name such as America/New_York is. It covers the libraries that supply the zone rules behind those calls. You need this when a zone object from another library reaches pandas, when behavior differs between pandas versions, or when a tz-aware datetime built outside pandas has a strange offset.
What a backend does
A pandas timestamp stores a count of nanoseconds since the Unix epoch in UTC. The time zone is a separate tzinfo object attached to that count. When pandas needs a wall-clock time, it asks the tzinfo object two questions:
- What is the UTC offset at this instant?
- At which instants does the offset change?
The answers come from the IANA time zone database. A Python library reads that database and exposes it as tzinfo objects. Three libraries do this:
| Backend | Where it comes from | How you name a zone |
|---|---|---|
| `zoneinfo` | Python standard library since 3.9 | `ZoneInfo("America/New_York")` |
| `pytz` | Third-party package | `pytz.timezone("America/New_York")` |
| `dateutil` | Third-party package | `dateutil.tz.gettz("America/New_York")` |
All three can describe the same rules. They differ in how you attach a zone to a plain datetime, and in how pandas treats them by default.
How pandas picks a backend
You usually pass a string such as "America/New_York" to tz_localize, tz_convert, pd.Timestamp(..., tz=...) or pd.date_range(..., tz=...). pandas turns the string into a tzinfo object. The rules are:
- A plain zone name uses pytz in the pandas 2.x series. pandas 3.0 changed the default to
zoneinfoand made pytz an optional dependency. - A name with the prefix
dateutil/, such as"dateutil/America/New_York", uses dateutil. "UTC"maps to a UTC singleton (datetime.timezone.utcin recent versions).- A
tzinfoobject you pass in is used as it is.
You can check which backend a given pandas version chose by looking at the module of the tz object:
import pandas as pd
ts = pd.Timestamp("2024-03-10 12:00", tz="America/New_York")
print(type(ts.tz).__module__)
# "zoneinfo" in pandas 3.x, "pytz.tzinfo" in pandas 2.x
ts_du = pd.Timestamp("2024-03-10 12:00", tz="dateutil/America/New_York")
print(type(ts_du.tz).__module__) # dateutil.tz.tzBecause the default depends on the version, avoid code that depends on the concrete class. Do not call ts.tz.zone, which exists only on pytz objects. Do not call ts.tz.key, which exists only on zoneinfo objects. If you need the name as a string, use str(ts.tz) for pytz and zoneinfo, and keep your own record of the name when you use dateutil.
Passing zone objects directly
When you want one explicit backend, pass its object instead of a string. pandas accepts all three, and the results agree:
import numpy as np
import pandas as pd
import dateutil.tz
import pytz
from zoneinfo import ZoneInfo
name = "America/New_York"
zones = {
"zoneinfo": ZoneInfo(name),
"pytz": pytz.timezone(name),
"dateutil": dateutil.tz.gettz(name),
}
# 2024-11-03 01:30 happens twice; True selects the first occurrence (EDT)
naive = pd.DatetimeIndex(["2024-11-03 01:30"])
for label, tz in zones.items():
aware = naive.tz_localize(tz, ambiguous=np.array([True]))
print(label, aware[0].isoformat()) # 2024-11-03T01:30:00-04:00 for eachEvery backend gives -04:00, so the ambiguous and nonexistent arguments from the DST chapter behave the same way. The backend does not change the rules, only the object that carries them.
Conversion also works across backends. tz_convert takes any of these objects as its argument, and the underlying UTC instant is unchanged.
The pytz trap with plain datetimes
The largest practical difference between the backends appears outside pandas, when you build a standard-library datetime and attach a zone to it. The datetime constructor accepts a tzinfo argument. zoneinfo and dateutil objects work with it correctly. pytz objects do not, because they are not designed for it.
A pytz zone object is really a family of fixed-offset objects, one per period in the zone's history. pytz.timezone("America/New_York") returns the first one, which is the offset from before standard time was adopted in 1883, called LMT (local mean time). Passing it as tzinfo gives a wrong offset:
from datetime import datetime
from zoneinfo import ZoneInfo
import pytz
name = "America/New_York"
wrong = datetime(2024, 7, 1, 12, 0, tzinfo=pytz.timezone(name))
print(wrong.utcoffset()) # -1 day, 19:04:00 (about -4:56, local mean time)
right = pytz.timezone(name).localize(datetime(2024, 7, 1, 12, 0))
print(right.utcoffset()) # -1 day, 20:00:00 (-4:00, EDT)
modern = datetime(2024, 7, 1, 12, 0, tzinfo=ZoneInfo(name))
print(modern.utcoffset()) # -1 day, 20:00:00 (-4:00, EDT)The correct pytz usage is the localize method. After arithmetic on a pytz-aware datetime, you also need normalize to fix the offset. With zoneinfo neither step is needed.
pandas hides this problem. tz_localize and tz="..." call the right pytz methods internally. The trap only appears when you build datetime objects yourself and then hand them to pandas, for example:
import pandas as pd
# datetime objects built with the wrong pytz usage carry the LMT offset
s = pd.Series([wrong])
print(s.iloc[0]) # 2024-07-01 12:00:00-04:56pandas keeps the offset it was given. The bad offset is data, not an error, so the timestamps are silently about 56 minutes off. If you receive datetime objects from other code, convert them once and check one value by hand.
Comparing the three
| Question | zoneinfo | pytz | dateutil |
|---|---|---|---|
| Part of the standard library | Yes, Python 3.9+ | No | No |
| Works as `datetime(..., tzinfo=tz)` | Yes | No, use `localize` | Yes |
| Needs `normalize` after arithmetic | No | Yes, on plain datetimes | No |
| Zone name attribute | `.key` | `.zone` | none reliable |
| Default for string names in pandas | 3.x | 2.x | only with `dateutil/` prefix |
| Handles ambiguous times by itself | Uses the `fold` attribute | Needs `is_dst` in `localize` | Uses the `fold` attribute |
Inside pandas, ambiguous and nonexistent work for all three, so the last row matters only for plain datetime code. The fold attribute is the standard way to pick the first (fold=0) or second (fold=1) occurrence of a repeated hour.
Choosing a backend
For new code, use zoneinfo:
- It is in the standard library, so there is nothing extra to install on Python 3.9 and later.
- It works with plain
datetimeobjects without special methods. - It is the default in pandas 3.x, so your code matches the library's direction.
Keep pytz only when you must. Typical reasons are an older pandas that you cannot upgrade, or a library in your stack that returns pytz objects and expects them back. Use dateutil when a project already depends on its tz module, for example for tz.tzlocal(), which represents the machine's local zone.
If your code must run on both pandas 2.x and 3.x, pass strings rather than backend objects, and avoid backend-specific attributes. Then the choice of backend becomes pandas' concern.
Pitfalls when mixing backends
- Pickles and cached data. A pickled DataFrame stores the tz object. Loading it on a machine without that backend installed fails. After upgrading from pandas 2 to 3, files pickled with pytz objects still need pytz present to load. Saving to Parquet stores a zone name instead, which avoids the issue.
- Backend-specific attributes. Code such as
ts.tz.zoneworks on pandas 2.x and raisesAttributeErroron pandas 3.x. Replace it withstr(ts.tz). - Different tz database versions. Each backend can read a different copy of the IANA database, such as the system copy or the
tzdatapackage. After a government changes its DST rules, an out-of-date copy produces wrong offsets for future dates. Keeptzdataupdated, and note that pytz bundles its own copy. - Local zone.
dateutil.tz.tzlocal()follows whatever the machine is set to. The same script gives different answers on different servers. Prefer an explicit zone name for anything stored or shared.
Summary of the working model
pandas stores UTC instants and defers all offset questions to a tzinfo object. The backend is only the source of that object. You can pass a name, which pandas resolves with its default backend, or an object from any of the three libraries. The results for tz-aware pandas operations are the same. Differences show up in plain datetime code, in version upgrades, and in pickled data.
Exercise
A colleague builds a column of Python datetime objects with datetime(2024, 7, 1, 12, tzinfo=pytz.timezone("America/New_York")) and puts them in a pandas Series. The values display with an offset of -04:56. What went wrong, and what are two ways to fix it?
Show answer
A pytz zone object used directly as tzinfo has the zone's earliest offset, local mean time (LMT, about -4:56 for New York), instead of the correct EDT offset of -4:00. Fix 1: build the datetime with pytz.timezone("America/New_York").localize(datetime(2024, 7, 1, 12)). Fix 2: use zoneinfo.ZoneInfo("America/New_York") as the tzinfo. Alternatively, build the datetimes naive and call tz_localize("America/New_York") on the Series through .dt.
Exercise
Your code runs ts.tz.zone to log the zone name. It works on pandas 2.x and fails on pandas 3.x. Why, and what is a version-independent replacement?
Show answer
pandas 2.x resolves zone-name strings to pytz objects, which have a .zone attribute. pandas 3.x resolves them to zoneinfo.ZoneInfo objects, which have .key instead. str(ts.tz) returns the zone name for both pytz and zoneinfo objects, so it works on both versions.
Exercise
You localize the same naive index with a zoneinfo zone, a pytz zone and a dateutil zone, all for America/New_York, and pass ambiguous=np.array([True]) for the time 2024-11-03 01:30. Will the resulting offsets differ between the three?
Show answer
No. All three report -04:00, because ambiguous=True selects the first occurrence (EDT) and every backend carries the same IANA rules. The backend changes the type of the tz object, not the result of tz_localize.