Sub topic 11
Working with time zones
This chapter assumes you can build a Series with a DatetimeIndex and parse strings with pd.to_datetime. It also assumes you know what a naive datetime is in Python.
Naive and aware timestamps
A naive timestamp has no time zone. 2024-03-10 12:00 could mean noon anywhere. An aware timestamp carries a zone, so it points to one exact instant. pandas treats the two as different kinds of data, and you cannot compare or subtract them.
Two methods change zone information, and they do different jobs:
| Method | Works on | What it does |
|---|---|---|
| `tz_localize` | Naive data | Attaches a zone. The wall-clock times stay the same. |
| `tz_convert` | Aware data | Changes the zone. The instant stays the same and the wall-clock times change. |
Localizing and converting
Suppose the naive times in your data were recorded in UTC. Attach that fact first, then convert for display.
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 printed index reads 2024-03-10 08:00:00-04:00 and 2024-03-10 09:00:00-04:00. New York had switched to daylight time that morning, so the offset is -04:00. Use IANA names such as America/New_York instead of fixed offsets like -05:00. IANA names carry the daylight saving rules, and fixed offsets do not.
For a regular column rather than an index, use the .dt accessor: df["when"].dt.tz_localize("UTC") and df["when"].dt.tz_convert("Asia/Tokyo").
Common errors
Calling the wrong method. tz_localize on aware data and tz_convert on naive data both raise TypeError. Check s.index.tz first. It is None for naive data.
Mixed offsets in text. Strings with different offsets cannot share one aware dtype. Parse them with utc=True, which converts everything to UTC.
mixed = ["2024-03-01 10:00+01:00", "2024-03-01 10:00-05:00"]
print(pd.to_datetime(mixed, utc=True))Comparing naive with aware. Subtracting or comparing the two raises TypeError. Localize the naive side first.
Daylight saving gaps and overlaps
Localizing local wall-clock times can fail twice a year. In spring, clocks skip an hour, so some local times do not exist. In autumn, clocks repeat an hour, so some local times are ambiguous. pandas raises an error by default, and you choose how to resolve it.
gap = pd.DatetimeIndex(["2024-03-10 02:30"])
print(gap.tz_localize("America/New_York", nonexistent="shift_forward"))
overlap = pd.DatetimeIndex(["2024-11-03 01:30"])
print(overlap.tz_localize("America/New_York", ambiguous=[True]))The first call moves the missing 02:30 forward to 03:00:00-04:00. In the second call, ambiguous=[True] selects the first occurrence, which is still daylight time (-04:00). Use ambiguous=[False] for the second occurrence (-05:00). You can also pass ambiguous="NaT" or nonexistent="NaT" to mark these rows as missing and review them later.
Practical rules
- Store and compute in UTC. Convert to local zones only for display or for calendar logic such as "which local day was this?".
- Localize as early as possible, right after parsing.
- Resample after converting to the zone whose calendar you want. A daily
resample("D")on UTC data cuts days at UTC midnight, not at local midnight. - Use
tz_convert(None)to turn aware data back into naive UTC. It drops the zone and keeps the UTC clock times.
Exercise
A DataFrame has a naive column when whose times were recorded in UTC. You need a column showing the same instants as Tokyo local time. Which two steps do you use, and in what order?
Show answer
First df["when"].dt.tz_localize("UTC") to mark the data as UTC. Then .dt.tz_convert("Asia/Tokyo") on the result. Localizing comes first because tz_convert only works on aware data.
Exercise
What does pd.to_datetime(["2024-03-01 10:00+01:00", "2024-03-01 10:00-05:00"], utc=True) give you, and why is utc=True needed?
Show answer
It gives a UTC-aware DatetimeIndex with 09:00 and 15:00 on 2024-03-01. The inputs have different offsets, so they cannot share one time zone dtype unless they are all converted to a common zone. utc=True does that conversion.