Sub topic 2
Converting Between Time Zones with `tz_convert`
Assume you know basic Python, pandas Series and DataFrame objects, and the difference between a date and a duration. This chapter focuses on data that already has a time zone.
Converting Between Zones with `tz_convert`
tz_convert changes how pandas displays an instant in another time zone. It preserves the instant, but changes the local clock time.
Use tz_localize to attach a zone to a naive timestamp. Use tz_convert only after the timestamp is time-zone aware.
import pandas as pd
ts_utc = pd.Timestamp("2024-03-10 12:00", tz="UTC")
print(ts_utc)
print(ts_utc.tz_convert("America/New_York"))The output is 08:00 in New York because both values describe the same instant.
The tz-Aware Dtype, `DatetimeIndex`, and `.dt`
A pandas container with one time zone uses a time-zone-aware datetime dtype, such as datetime64[ns, UTC]. A DatetimeIndex has direct .tz_convert() support. A datetime Series uses the .dt accessor.
| Object | Conversion syntax |
|---|---|
| `Timestamp` | `value.tz_convert("UTC")` |
| `DatetimeIndex` | `index.tz_convert("UTC")` |
| datetime `Series` | `series.dt.tz_convert("UTC")` |
import pandas as pd
s = pd.Series(pd.to_datetime(
["2024-01-15 09:30", "2024-07-15 09:30"]
)).dt.tz_localize("America/New_York")
print(s.dtype)
print(s.dt.tz_convert("UTC"))New York uses different UTC offsets in winter and summer. pandas applies the correct offset for each value.
Parsing Strings with UTC Offsets
When input strings contain offsets, pass utc=True to normalize them into one aware UTC result. This avoids mixed-offset object data.
import pandas as pd
raw = ["2024-01-01T00:00:00+01:00", "2024-06-01T00:00:00+02:00"]
parsed = pd.to_datetime(raw, utc=True)
print(parsed)Comparing and Subtracting Aware Timestamps
Both timestamps must be aware, or both must be naive. Comparing a naive timestamp with an aware timestamp raises TypeError. Aware timestamps can be compared and subtracted even when their zones differ.
import pandas as pd
start = pd.Timestamp("2024-01-01 09:00", tz="America/New_York")
end = pd.Timestamp("2024-01-01 15:00", tz="UTC")
print(end > start)
print(end - start)Exercise
Which method should you use to display an aware UTC timestamp in Tokyo time?
Show answer
Use timestamp.tz_convert("Asia/Tokyo").