Sub topic 5
The tz-aware dtype, DatetimeIndex and .dt
This chapter assumes you can already attach a zone with tz_localize and change it with tz_convert on a single Timestamp. You should also know basic Series and DataFrame indexing. Here the focus moves from single timestamps to columns and indexes. You will see what pandas stores, how the dtype records the zone, and which accessor or method to call on each container.
What the tz-aware dtype is
A tz-aware column has its own dtype, DatetimeTZDtype. Its display name has the form datetime64[unit, zone], for example datetime64[ns, Asia/Tokyo]. A naive column has the plain datetime64[ns] dtype with no zone.
import pandas as pd
s = pd.Series(pd.to_datetime(["2024-07-15 23:30", "2024-07-16 00:30"]))
print(s.dtype) # datetime64[ns]
aware = s.dt.tz_localize("UTC")
print(aware.dtype) # datetime64[ns, UTC]
print(isinstance(aware.dtype, pd.DatetimeTZDtype)) # True
dtype = pd.DatetimeTZDtype(tz="Asia/Tokyo")
print(dtype.tz) # Asia/Tokyo
print(dtype.unit) # nsInternally, pandas stores every value as a count of time units since 1970-01-01 00:00 UTC. The zone is a label attached to the whole column. Because of this, tz_convert is cheap. It changes the label and leaves the stored numbers alone. Two columns in different zones can hold the same instants, and comparing them gives True:
import pandas as pd
utc = pd.Series(pd.to_datetime(["2024-07-15 23:30", "2024-07-16 00:30"])).dt.tz_localize("UTC")
tokyo = utc.dt.tz_convert("Asia/Tokyo")
print((utc == tokyo).all()) # True
print(tokyo.dtype) # datetime64[ns, Asia/Tokyo]To test whether a column is tz-aware, check the dtype with isinstance(s.dtype, pd.DatetimeTZDtype). The older helper pd.api.types.is_datetime64tz_dtype is deprecated.
::: :::
One zone per column
A tz-aware dtype carries exactly one zone. If you build a column from timestamps in different zones, pandas cannot pick one dtype, so it falls back to object. Each element then keeps its own zone.
import pandas as pd
mixed = pd.Series([
pd.Timestamp("2024-01-01 09:00", tz="UTC"),
pd.Timestamp("2024-01-01 09:00", tz="Asia/Tokyo"),
])
print(mixed.dtype) # object
fixed = pd.to_datetime(mixed, utc=True)
print(fixed.dtype) # datetime64[ns, UTC]
print(fixed.tolist())An object column is slow, and .dt does not work on it. Converting with pd.to_datetime(..., utc=True) is the usual repair. It turns every element into an instant in UTC and gives you one dtype. If you need local times afterwards, call .dt.tz_convert(...) on the result. A later chapter covers parsing strings that carry offsets.
DatetimeIndex
A DatetimeIndex is the index version of the same idea. It has a .tz attribute and the same methods, without the .dt prefix.
import pandas as pd
idx = pd.date_range("2024-03-09 12:00", periods=4, freq="6h", tz="UTC")
print(idx.tz) # UTC
ny = idx.tz_convert("America/New_York")
print(ny.tz) # America/New_York
print(ny.hour.tolist()) # [7, 13, 19, 1]
print(ny[0]) # 2024-03-09 07:00:00-05:00Starting at 12:00 UTC, the first value is 07:00 in New York (UTC−5 before the clocks change). The last value is 01:00 on March 10, still before the 02:00 spring-forward jump.
If you set a tz-aware column as the index, the zone carries over:
import pandas as pd
df = pd.DataFrame({
"ts": pd.date_range("2024-01-01", periods=3, freq="D", tz="Europe/Paris"),
"value": [10, 20, 30],
})
indexed = df.set_index("ts")
print(type(indexed.index).__name__) # DatetimeIndex
print(indexed.index.tz) # Europe/ParisYou cannot assign to idx.tz directly. Use tz_localize or tz_convert, which return a new object.
Slicing uses the index's local time
When you slice a series by a date string, pandas interprets the string in the index's zone. A local day is selected by local midnight to local midnight, which is not always 24 hours.
import pandas as pd
idx = pd.date_range("2024-03-09 12:00", periods=48, freq="h", tz="America/New_York")
ts = pd.Series(range(48), index=idx)
print(len(ts.loc["2024-03-09"])) # 12
print(len(ts.loc["2024-03-10"])) # 23March 10, 2024 is the spring-forward day in New York. It has only 23 hours, so the string "2024-03-10" selects 23 rows. If you had converted the index to UTC first, the same string would select a different set of rows.
The .dt accessor
On a Series with a datetime dtype, .dt exposes datetime properties and methods. Two groups matter for time zones.
Component properties such as hour, day, dayofweek and date return the wall-clock value in the column's own zone:
import pandas as pd
utc = pd.Series(pd.to_datetime(["2024-07-15 23:30", "2024-07-16 00:30"])).dt.tz_localize("UTC")
local = utc.dt.tz_convert("Asia/Tokyo")
print(utc.dt.day.tolist()) # [15, 16]
print(local.dt.day.tolist()) # [16, 16]
print(local.dt.hour.tolist()) # [8, 9]
print(local.dt.normalize().nunique()) # 1The same two instants fall on different days depending on the zone. If you group or filter by .dt.day or .dt.date, convert to the zone you care about first. normalize() sets the time to local midnight and keeps the zone, which makes it a convenient key for local-day grouping.
Zone methods are tz_localize, tz_convert and the tz attribute. Rounding methods floor, ceil and round also exist on .dt, and they work in local wall-clock time. Rounding across a DST change can raise the same ambiguous or nonexistent errors as tz_localize, so use the ambiguous and nonexistent arguments if you hit them.
Which method for which container
| Object | Zone methods | Acts on |
|---|---|---|
| `Timestamp` | `ts.tz_localize`, `ts.tz_convert` | The single value |
| `DatetimeIndex` | `idx.tz_localize`, `idx.tz_convert` | The index values |
| `Series` of datetimes | `s.dt.tz_localize`, `s.dt.tz_convert` | The values |
| `Series` or `DataFrame` | `s.tz_localize`, `s.tz_convert` | The index, not the values |
The last row is a common source of mistakes. Series.tz_localize and DataFrame.tz_convert exist, but they work on the index along an axis, not on a datetime column.
import pandas as pd
s = pd.Series([1, 2], index=pd.to_datetime(["2024-01-01", "2024-01-02"]))
print(s.tz_localize("UTC").index.tz) # UTCIf the index is not a DatetimeIndex, for example the default RangeIndex, calling s.tz_localize("UTC") raises a TypeError. The fix is to call s.dt.tz_localize("UTC") on the datetime column instead.
Choosing the operation from the dtype
The dtype decides which operation is legal. Localizing needs a naive column, and converting needs an aware one. Passing None removes the zone.
The two arrows back to naive differ. tz_localize(None) drops the zone and keeps the local clock reading. tz_convert(None) first converts to UTC and then drops the zone. Chapter 11 covers when to use each before saving data.
Common errors with the dtype and .dt
Each of these errors comes from the dtype not matching the method you called.
import pandas as pd
naive = pd.Series(pd.to_datetime(["2024-01-01 10:00"]))
aware = naive.dt.tz_localize("UTC")
text = pd.Series(["2024-01-01 10:00"])
try:
naive.dt.tz_convert("UTC")
except TypeError as e:
print(e) # Cannot convert tz-naive timestamps, use tz_localize to localize
try:
aware.dt.tz_localize("Asia/Tokyo")
except TypeError as e:
print(e) # Already tz-aware, use tz_convert to convert.
try:
text.dt.tz_localize("UTC")
except AttributeError as e:
print(e) # Can only use .dt accessor with datetimelike valuestz_converton a naive column fails because pandas will not guess the original zone. Localize first.tz_localizeon an aware column fails because the data already has a zone. Usetz_convert, or drop the zone withtz_localize(None)before localizing again if the stored zone was wrong..dton an object or string column fails. Parse withpd.to_datetimefirst. An object column that holds mixed zones needsutc=True, as shown earlier.
Working practices
- Keep data in UTC inside your pipeline and convert to a local zone only for grouping or display. This keeps each column a single clean dtype.
- Check
df.dtypesafter loading data. A column that showsobjectwhere you expecteddatetime64[ns, UTC]usually means mixed offsets or mixed zones. - Convert to the target zone before using
.dt.date,.dt.dayor.dt.hour. These properties read the column's current zone. - Use string slicing on a tz-aware index only when you mean local days in the index's zone.
Exercise
A DataFrame column ts has dtype datetime64[ns, UTC]. You want a column with the local calendar date in America/Chicago. Write the expression, and explain why df["ts"].dt.date alone would be wrong.
Show answer
Use df["ts"].dt.tz_convert("America/Chicago").dt.date. The .dt.date property reads the wall-clock value in the column's current zone. On the UTC column it returns the UTC date, which differs from the Chicago date for any timestamp between midnight and 05:00 or 06:00 UTC. Convert first, then extract the date.
Exercise
You call df.tz_localize("UTC") on a DataFrame whose default integer index has a datetime column when. What happens, and what should you call instead?
Show answer
It raises a TypeError, because DataFrame.tz_localize works on the index and the index is not a DatetimeIndex. Call df["when"] = df["when"].dt.tz_localize("UTC") to localize the column, or set when as the index first with df.set_index("when") and then localize the index.