Sub topic 11
Working with time zones
This chapter assumes you can build a DatetimeIndex, parse text with pd.to_datetime, and select rows by partial date strings. Those are covered in earlier chapters. Here you will learn how pandas attaches a time zone to timestamps, how to convert between zones, and how to handle daylight saving time (DST) without silent errors.
Naive and aware timestamps
pandas has two kinds of datetime values.
- A naive timestamp has no time zone.
2024-03-10 12:00is only a wall-clock reading, and nothing says where that clock is. - An aware timestamp carries a time zone.
2024-03-10 08:00:00-04:00names one exact instant in time.
Internally, an aware value stores the instant as a UTC count since the epoch. The zone only controls how that instant is displayed and which calendar fields (hour, day, weekday) you get when you read it. So converting between zones never changes the instant. It changes the wall-clock labels.
Most parsed data starts out naive. Two methods change that, and they do different things.
| Method | Starts from | What it does | Changes the instant? |
|---|---|---|---|
| `tz_localize(tz)` | naive | Declares which zone the wall-clock readings belong to | Yes, because the readings are now tied to a zone |
| `tz_convert(tz)` | aware | Re-expresses the same instant in another zone | No |
Calling tz_convert on a naive value raises TypeError. Calling tz_localize on an aware value, with a zone name, also raises TypeError. These errors help, because they stop you from guessing.
Localizing and converting
Use tz_localize to say what zone naive data was recorded in. Then use tz_convert to view it elsewhere.
import pandas as pd
s = pd.Series(
[1, 2],
index=pd.to_datetime(["2024-03-10 12:00", "2024-03-10 13:00"]),
)
s_utc = s.tz_localize("UTC")
s_ny = s_utc.tz_convert("America/New_York")
print(s_ny)The output shows 2024-03-10 08:00:00-04:00 and 2024-03-10 09:00:00-04:00. The series is indexed by time, so both methods act on the index. On a DataFrame with a datetime column, use the .dt accessor instead:
import pandas as pd
df = pd.DataFrame({"when": pd.to_datetime(["2024-06-01 23:30", "2024-06-02 00:30"])})
df["when"] = df["when"].dt.tz_localize("UTC")
df["when_tokyo"] = df["when"].dt.tz_convert("Asia/Tokyo")
print(df)
print(df.dtypes)The dtype of an aware column is datetime64[..., <zone>], where the unit (ns, us, and so on) depends on your pandas version. A column has one zone. If you need two views of the same instants, keep two columns, as above.
A single Timestamp accepts the zone at construction:
import pandas as pd
t = pd.Timestamp("2024-03-10 12:00", tz="UTC")
print(t.tz_convert("Europe/Berlin"))Choosing zone names
Use IANA names such as "UTC", "Europe/Berlin", or "America/New_York". They carry the full history of DST rules for that region. Abbreviations like "EST" or "CST" are ambiguous (there are several "CST" zones) and do not follow DST changes, so avoid them. A fixed offset such as "+05:30" is fine for regions without DST, but it will be wrong across a DST change.
Parsing text that contains offsets
If your strings include a UTC offset, the parser creates aware values. When every string has the same offset, you get a fixed-offset dtype. When offsets differ, the result depends on your pandas version. Older and current 2.x versions can fall back to an object column of Python datetimes, with a warning, and that column loses all the fast datetime methods. Pass utc=True to avoid this:
import pandas as pd
raw = ["2024-03-01 09:00+01:00", "2024-03-01 09:00-05:00"]
parsed = pd.to_datetime(raw, utc=True)
print(parsed)
print(parsed.tz_convert("America/New_York"))With utc=True, pandas converts every value to UTC. This works on naive strings too, because it treats them as already being UTC. It does not convert them. So use it only when naive strings really are UTC, and otherwise parse first and then call tz_localize with the true zone.
Daylight saving time edge cases
Localizing a naive value to a DST zone is where most errors appear, because wall-clock times are not always unique or valid.
- Ambiguous times. When clocks fall back, one hour happens twice. In New York on 2024-11-03,
01:30occurs at both 05:30 UTC and 06:30 UTC. - Nonexistent times. When clocks spring forward, one hour never happens. On 2024-03-10,
02:30was skipped in New York.
By default, tz_localize raises an error for both. You choose how to resolve them with the ambiguous and nonexistent arguments.
import pandas as pd
amb = pd.DatetimeIndex(["2024-11-03 01:30"])
try:
amb.tz_localize("America/New_York")
except Exception as exc:
print("ambiguous:", type(exc).__name__)
print(amb.tz_localize("America/New_York", ambiguous=[True])) # first occurrence, still DST
print(amb.tz_localize("America/New_York", ambiguous=[False])) # second occurrence, standard time
print(amb.tz_localize("America/New_York", ambiguous="NaT"))
gap = pd.DatetimeIndex(["2024-03-10 02:30"])
print(gap.tz_localize("America/New_York", nonexistent="shift_forward"))
print(gap.tz_localize("America/New_York", nonexistent="NaT"))ambiguous=[True] marks the value as DST, so it resolves to 01:30-04:00. [False] gives 01:30-05:00. The list has one boolean per element. ambiguous="NaT" gives you a missing value to inspect later. For nonexistent, "shift_forward" moves the time to the first valid moment after the gap (03:00-04:00), and "shift_backward" moves it before the gap.
The cleanest fix is upstream: store timestamps in UTC, or with explicit offsets, so that no ambiguity exists. Local wall time without an offset cannot be fully recovered once it falls in a repeated hour.
Arithmetic across DST changes
Aware timestamps compare and subtract by instant. Adding a fixed duration adds elapsed time, not wall-clock time. A calendar day is not always 24 hours. The "D" frequency in date_range steps by calendar days in local time, while "24h" steps by exactly 24 elapsed hours.
import pandas as pd
days = pd.date_range("2024-03-09", periods=3, freq="D", tz="America/New_York")
hours = pd.date_range("2024-03-09", periods=3, freq="24h", tz="America/New_York")
print(days)
print(hours)
print(pd.Series(days).diff())The days index lands on midnight each day. Because the clocks changed on March 10, the gap between the second and third midnights is 23 hours. The hours index drifts to 01:00-04:00 on the third entry, because 24 real hours have passed.
Use calendar steps for things like "every morning at 9:00" and elapsed steps for things like sensor readings that are exactly one day apart.
Naive and aware values do not mix
Comparing or subtracting a naive value with an aware one raises TypeError. pandas refuses because it cannot know which zone the naive value belongs to.
import pandas as pd
aware = pd.Series(pd.to_datetime(["2024-03-10 12:00"])).dt.tz_localize("UTC")
naive = pd.Series(pd.to_datetime(["2024-03-10 12:00"]))
try:
print(aware > naive)
except TypeError as exc:
print("TypeError:", exc)Two columns that are both aware but in different zones can be compared, because pandas compares the instants. Merging or concatenating them may produce an object column or a UTC column, depending on the operation. To avoid surprises, convert both sides to one zone before you join.
To strip a zone, choose what you want to keep:
tz_localize(None)removes the zone and keeps the local wall-clock readings.tz_convert(None)converts to UTC first, then removes the zone.
For a series in America/New_York showing 08:00-04:00, the first gives 08:00 and the second gives 12:00.
Grouping by local calendar day
The day boundary depends on the zone. Events at 23:30 and 00:30 UTC fall on different UTC days but on the same day in Tokyo. Convert before you resample.
import pandas as pd
events = pd.Series(
[1, 1],
index=pd.to_datetime(["2024-06-01 23:30", "2024-06-02 00:30"]),
).tz_localize("UTC")
print(events.resample("D").count())
print(events.tz_convert("Asia/Tokyo").resample("D").count())The first result has two rows (June 1 and June 2, one event each). The second has one row (June 2, two events). Choose the zone that matches the question you are answering, such as the customer's local day or the company's reporting day.
Debugging checklist
- Print
df.dtypes. A zone appears inside the dtype, such asdatetime64[ns, UTC]. If it showsobject, mixed offsets or mixed naive and aware values are the likely cause. - Check
series.dt.tz(orindex.tz).Nonemeans naive. - On
TypeErrorfrom a comparison, find the naive side and localize it. - On an ambiguous or nonexistent time error, filter the rows near the DST dates and decide how to resolve them.
- If counts per day look off by one hour or one day, check which zone the resample ran in.
Exercise
A DataFrame column ts holds naive timestamps that were recorded in UTC. Write the code to add a column local_day containing the calendar date in Australia/Sydney, and explain why calling tz_convert directly on the naive column would fail.
Show answer
Use df["ts"] = df["ts"].dt.tz_localize("UTC") and then df["local_day"] = df["ts"].dt.tz_convert("Australia/Sydney").dt.date. You must localize first because tz_convert only changes the zone of values that already have one. On naive values, pandas does not know which zone the readings belong to, so it raises a TypeError. Localizing declares that the readings are UTC, and converting then re-expresses the same instants in Sydney time before the date is read.
Exercise
The time 2024-11-03 01:30 in America/New_York can be localized in two ways. What UTC offsets can the results have, and which argument selects between them?
Show answer
It can be 01:30-04:00 (the first occurrence, still on daylight time) or 01:30-05:00 (the second occurrence, on standard time). The ambiguous argument of tz_localize selects between them: True for the DST occurrence, False for the standard-time occurrence. Without it, pandas raises an error.