Sub topic 5
The tz-aware dtype, DatetimeIndex and .dt
This chapter assumes you know basic Python, pandas Series and DataFrame basics, and how to attach a zone with tz_localize and change it with tz_convert on a single Timestamp. Here you will see how the same operations work on whole columns and indexes, and what the dtype tells you.
The tz-aware dtype
A pandas datetime column is either naive or aware, and the dtype shows which. A naive column has dtype datetime64[ns]. An aware column has dtype datetime64[ns, <zone>], where the zone is part of the dtype. The unit can differ (for example us or s) depending on how the data was created and your pandas version, but the zone always appears after the comma.
Every value in an aware column shares one zone. A single column cannot hold New York and Tokyo times side by side as datetimes. If you try to mix zones, pandas falls back to object dtype, which is slow and loses the datetime methods. Convert everything to one zone first.
Two containers, two APIs
The zone operations live in different places depending on the container:
| Container | Localize | Convert | Inspect |
|---|---|---|---|
| `Timestamp` | `ts.tz_localize(tz)` | `ts.tz_convert(tz)` | `ts.tzinfo` |
| `DatetimeIndex` | `idx.tz_localize(tz)` | `idx.tz_convert(tz)` | `idx.tz` |
| `Series` | `s.dt.tz_localize(tz)` | `s.dt.tz_convert(tz)` | `s.dt.tz` |
A Series needs the .dt accessor, which exposes datetime-specific methods and properties for a column of datetimes. A DatetimeIndex has the methods directly. A common error is calling s.tz_localize("UTC") on a Series. That method exists, but it acts on the Series index, not the values, and raises an error if the index is not a DatetimeIndex.
import pandas as pd
s = pd.Series(pd.to_datetime(["2024-01-15 09:30", "2024-07-15 09:30"]))
print(s.dt.tz) # None, the column is naive
s_ny = s.dt.tz_localize("America/New_York")
print(s_ny.dt.tz) # America/New_York
print(s_ny.dtype) # datetime64[ns, America/New_York]The same column can be converted in one step to UTC:
s_utc = s_ny.dt.tz_convert("UTC")
print(s_utc)
# 0 2024-01-15 14:30:00+00:00
# 1 2024-07-15 13:30:00+00:00The New York offset is -05:00 in January and -04:00 in July. The conversion applies the right offset to each row. The UTC time differs by an hour even though both local times are 09:30.
Zones on an index
When timestamps are the index of a DataFrame, you work on the index. Assign the result back, because these methods return new objects.
import pandas as pd
df = pd.DataFrame(
{"value": [1, 2, 3]},
index=pd.date_range("2024-01-01 00:00", periods=3, freq="h"),
)
df.index = df.index.tz_localize("UTC")
print(df.index.tz) # UTC
df_ny = df.tz_convert("America/New_York")
print(df_ny.index[0]) # 2023-12-31 19:00:00-05:00Here df.tz_convert(...) converts the index. On a DataFrame or Series, tz_localize and tz_convert operate on the index (axis 0 by default). Use .dt when the datetimes are in a column.
You can also create an aware index directly with the tz argument:
import pandas as pd
idx = pd.date_range("2024-06-01", periods=3, freq="D", tz="Europe/Paris")
print(idx.dtype) # datetime64[ns, Europe/Paris]Reading components from aware data
The .dt accessor properties such as .year, .hour and .day_name() return values in the column's own zone, not in UTC. This matters when you extract the hour from a UTC column and the result is not the hour a person in your city would see.
import pandas as pd
s = pd.Series(pd.to_datetime(["2024-01-01 02:00"])).dt.tz_localize("UTC")
print(s.dt.hour.iloc[0]) # 2
print(s.dt.tz_convert("Asia/Tokyo").dt.hour.iloc[0]) # 11Convert to the zone you care about first, then extract components.
Common errors
- Calling
tz_localizeon an already aware object raisesTypeError("Already tz-aware, use tzconvert to convert"). Use `tzconvert` to change zones. - Calling
tz_converton a naive object raisesTypeError("Cannot convert tz-naive timestamps, use tz_localize to localize"). Localize first. - Forgetting to assign the result back leaves the original unchanged.
Exercise
A DataFrame has a column ts of naive datetimes recorded in London local time. Write the code to turn it into a UTC column, and explain why df["ts"].tz_localize("Europe/London") is the wrong call.
Show answer
Use df["ts"] = df["ts"].dt.tz_localize("Europe/London").dt.tz_convert("UTC"). First localize to attach the London zone, then convert to UTC. Calling tz_localize directly on the Series, without .dt, acts on the Series index instead of its values, so it either fails or localizes the wrong thing.