Sub topic 3
Attaching a time zone with tz_localize
This chapter assumes you know basic Python, pandas Series and DataFrame operations, and the difference between a date, a time and a timedelta. It also assumes you know what a tz-naive timestamp is, meaning one with no zone attached. The next chapter covers tz_convert.
What tz_localize does
A tz-naive timestamp holds a wall-clock reading such as 2024-03-10 12:00. It does not say which instant that is. tz_localize supplies the missing information. It tells pandas which time zone the existing wall-clock reading belongs to.
tz_localize does not change the clock reading. It only attaches the zone, which pins the reading to one instant on the global timeline.
import pandas as pd
ts = pd.Timestamp("2024-03-10 12:00")
print(ts.tzinfo) # None
print(ts.tz_localize("UTC")) # 2024-03-10 12:00:00+00:00
print(ts.tz_localize("America/New_York")) # 2024-03-10 12:00:00-04:00
print(ts.tz_localize("Asia/Tokyo")) # 2024-03-10 12:00:00+09:00All three results read 12:00, but they are three different instants, because noon happens at different moments in each zone. Choosing the zone is a factual claim about your data: "these readings were recorded on a clock set to this zone." pandas cannot check that claim.
Which method to call
tz_localize exists on several pandas objects, and they differ in what they act on.
| Object | Call | What gets localized |
|---|---|---|
| `Timestamp` | `ts.tz_localize(tz)` | The single timestamp |
| `DatetimeIndex` | `idx.tz_localize(tz)` | The index values |
| `Series` of datetimes | `s.dt.tz_localize(tz)` | The values in the Series |
| `Series` with a datetime index | `s.tz_localize(tz)` | The index, not the values |
| `DataFrame` | `df.tz_localize(tz)` | The index (or columns with `axis=1`), not column values |
The last two rows catch many people. Series.tz_localize and DataFrame.tz_localize work on the index. To localize a datetime column, go through .dt.
import pandas as pd
# A Series whose index holds the timestamps
s = pd.Series([10, 20, 30], index=pd.date_range("2024-06-01", periods=3, freq="D"))
s_utc = s.tz_localize("UTC")
print(s_utc.index.tz) # UTC
# A DataFrame whose column holds the timestamps
df = pd.DataFrame({
"when": pd.to_datetime(["2024-06-01 08:00", "2024-06-01 17:30"]),
"value": [1, 2],
})
df["when"] = df["when"].dt.tz_localize("Europe/Berlin")
print(df["when"].dt.tz) # Europe/Berlin
print(df["when"].iloc[0]) # 2024-06-01 08:00:00+02:00The .dt accessor works only on columns that already have a datetime dtype. If the column holds strings, with dtype object, df["when"].dt raises AttributeError. Parse the column with pd.to_datetime first, then localize.
Setting the zone at creation with tz
You often don't need a separate localizing step. Several constructors accept a tz argument and build aware data directly.
import pandas as pd
a = pd.Timestamp("2024-01-01 09:00", tz="Europe/Paris")
print(a) # 2024-01-01 09:00:00+01:00
idx = pd.date_range("2024-01-01", periods=3, freq="D", tz="Europe/Paris")
same = pd.date_range("2024-01-01", periods=3, freq="D").tz_localize("Europe/Paris")
print(idx.equals(same)) # True
print(idx[0]) # 2024-01-01 00:00:00+01:00When you pass tz to pd.Timestamp, pd.DatetimeIndex or pd.date_range, the string is interpreted as a wall-clock time in that zone. This matches tz_localize. Passing tz to pd.date_range has one more benefit. The range is generated in local time, so it is aware of DST changes. A later chapter shows why that matters.
pd.to_datetime has no tz argument that behaves this way. It takes utc=True, which treats naive input as UTC and converts offsets to UTC. To attach any other zone to parsed strings, parse first and then call .dt.tz_localize.
Choosing the zone name
The tz argument accepts these forms:
- An IANA name such as
"America/New_York"or"Europe/Berlin". This is the right choice for local clock times, because the name carries the full DST history for that region. "UTC", which has no daylight saving and never produces ambiguous times.- A fixed offset, such as
datetime.timezone(datetime.timedelta(hours=5, minutes=30)). A fixed offset never changes. It is correct only when the source really used a constant offset. - A
tzinfoobject fromzoneinfo,pytzordateutil. Backends are covered in a later chapter.
As a rule, use IANA names for human-facing local data and UTC for machine-generated data. Avoid abbreviations such as "EST" or "CST". They are ambiguous and hide DST behavior.
A decision flow
Before you call anything, check whether the data is already aware. Inspect tzinfo on a Timestamp or .tz on an index. For a Series, use .dt.tz.
Localizing aware data raises an error
tz_localize only attaches a zone to naive data. If a zone is already present, pandas refuses to guess whether you want to replace it or convert it.
import pandas as pd
aware = pd.Timestamp("2024-03-10 12:00", tz="UTC")
try:
aware.tz_localize("America/New_York")
except TypeError as e:
print(type(e).__name__) # TypeError
idx = pd.date_range("2024-01-01", periods=2, freq="h", tz="UTC")
try:
idx.tz_localize("Asia/Tokyo")
except TypeError as e:
print(type(e).__name__) # TypeError
print(aware.tz_convert("America/New_York")) # 2024-03-10 08:00:00-04:00If you want to see the same instant on another clock, use tz_convert. If you really do want to keep the wall-clock reading and swap the zone, which happens when a source mislabeled its data, first remove the zone and then attach the right one:
import pandas as pd
mislabeled = pd.Timestamp("2024-03-10 12:00", tz="UTC")
fixed = mislabeled.tz_localize(None).tz_localize("America/New_York")
print(fixed) # 2024-03-10 12:00:00-04:00tz_localize(None) drops the zone and keeps the local reading. This is different from tz_convert(None), which converts to UTC and then drops the zone.
Local times that don't map to one instant
Attaching a zone to a wall-clock reading is only well defined if that reading happens exactly once on that zone's clock. Daylight saving transitions break this in two ways.
- Ambiguous times. When clocks fall back, an hour repeats.
2024-11-03 01:30in New York happens twice, once at -04:00 and once at -05:00. - Nonexistent times. When clocks spring forward, an hour is skipped.
2024-03-10 02:30in New York never happens.
By default tz_localize raises an error for both. The ambiguous and nonexistent arguments choose how to resolve them. The next chapters work through all the options. Here is a short example of the most common fix.
import pandas as pd
tz = "America/New_York"
missing = pd.Timestamp("2024-03-10 02:30")
try:
missing.tz_localize(tz)
except Exception as e:
print(type(e).__name__) # NonExistentTimeError
print(missing.tz_localize(tz, nonexistent="shift_forward"))
# 2024-03-10 03:00:00-04:00An error here is useful. It tells you the data contains a reading that cannot be correct for that zone, which often means the source recorded in a different zone from the one you assumed.
Common errors and how to read them
TypeErrorontz_localize. The data is already aware. Usetz_convert, or calltz_localize(None)first if you need to replace the zone.AttributeError: Can only use .dt accessor with datetimelike values. The column is not a datetime dtype. Parse it withpd.to_datetime.- The index changed but the column did not. You called
Series.tz_localizeorDataFrame.tz_localize, which act on the index. Use.dt.tz_localizefor column values. AmbiguousTimeErrororNonExistentTimeError. The reading falls in a DST transition. Pick a resolution withambiguousornonexistent, or localize the data as UTC if that is how it was recorded.- Times are off by whole hours but nothing failed. The zone you chose does not match the source. Check how the data was produced.
Summary
tz_localize takes naive timestamps and attaches a zone without changing the clock reading. Use it on Timestamp and DatetimeIndex objects directly, and use .dt.tz_localize for Series values. Remember that Series.tz_localize and DataFrame.tz_localize act on the index. Constructors such as pd.Timestamp and pd.date_range accept tz and give the same result. The method raises TypeError on data that is already aware, and it raises DST errors by default unless you choose a resolution.
Exercise
A DataFrame df has a string column "logged" with values like "2024-07-04 18:00", recorded on servers that use Europe/London local time. Write the two lines that turn this column into tz-aware values in that zone. Then say what df["logged"].iloc[0] would show, given July's offset.
Show answer
df["logged"] = pd.todatetime(df["logged"]) df["logged"] = df["logged"].dt.tzlocalize("Europe/London") The first line parses the strings so the column has a datetime dtype, which the .dt accessor requires. The second attaches the zone without moving the clock reading. In July, London is on British Summer Time, so the first value shows 2024-07-04 18:00:00+01:00.
Exercise
You call s.tz_localize("UTC") on a Series s that has a plain integer index and a datetime column stored elsewhere. What happens, and what should you call instead to localize datetime values stored in a Series?
Show answer
Series.tzlocalize acts on the index, so with an integer index (not a DatetimeIndex) it raises a TypeError, because there is nothing datetime-like to localize. To localize datetime values held in a Series, call s.dt.tzlocalize("UTC") on the Series of datetimes.
Exercise
A Timestamp t was created with tz="UTC" but the source actually recorded New York wall-clock time. How do you fix it so the reading stays the same and the zone becomes America/New_York?
Show answer
t.tzlocalize(None).tzlocalize("America/NewYork"). The first call removes the UTC label and keeps the clock reading. The second attaches the correct zone. Calling tzlocalize directly on t would raise a TypeError, and tz_convert would change the reading instead of keeping it.