Sub topic 3
Attaching a time zone with tz_localize
This chapter assumes you know basic Python, pandas Series and DataFrames, and datetime ideas such as dates, times and timedeltas. It also assumes you know the difference between naive and aware timestamps and what IANA zone names like America/New_York are. Here you will use tz_localize to turn naive data into aware data.
What tz_localize does
tz_localize attaches a time zone to naive data. The wall-clock reading stays the same, and pandas now interprets it as local time in that zone. The underlying instant is whatever that local reading means in the zone you named.
This differs from tz_convert, which keeps the instant and changes the displayed zone. Use tz_localize when you know what zone the naive values were recorded in. Use tz_convert afterward to view them elsewhere.
import pandas as pd
ts = pd.Timestamp("2024-03-10 12:00")
print(ts.tzinfo) # None, so this timestamp is naive
ts_utc = ts.tz_localize("UTC")
print(ts_utc) # 2024-03-10 12:00:00+00:00
print(ts_utc.tz_convert("America/New_York")) # 2024-03-10 08:00:00-04:00The localized value still reads 12:00. Only after tz_convert does the clock reading change to 08:00.
Localizing a Series or index
A Series needs the .dt accessor. A DatetimeIndex has tz_localize directly.
import pandas as pd
s = pd.Series(pd.to_datetime(["2024-01-15 09:30", "2024-07-15 09:30"]))
s_ny = s.dt.tz_localize("America/New_York")
s_utc = s_ny.dt.tz_convert("UTC")
print(s_ny.dtype) # datetime64[ns, America/New_York]
print(s_utc) # 14:30 UTC in January, 13:30 UTC in JulyBoth inputs read 09:30, but the results differ in UTC. New York is five hours behind UTC in January and four hours behind in July, and the IANA zone name carries that rule. A fixed offset such as UTC-5 would give the wrong answer for July.
Creating aware data directly
Often you can skip the two-step process. Many constructors accept a tz argument.
import pandas as pd
a = pd.Timestamp("2024-06-01 08:00", tz="Europe/Paris")
idx = pd.date_range("2024-06-01", periods=3, freq="h", tz="Europe/Paris")
print(a)
print(idx)Use tz_localize when the data already exists as naive values, for example a column read from a CSV file.
Common errors
Localizing a value that is already aware raises a TypeError. Use tz_convert to change zones.
import pandas as pd
aware = pd.Timestamp("2024-01-01", tz="UTC")
try:
aware.tz_localize("Europe/Paris")
except TypeError as e:
print(e) # Cannot localize tz-aware Timestamp, use tz_convert for conversionsIf you want to discard a zone, call tz_localize(None). A later chapter covers that.
Mixing naive and aware values in a comparison also fails.
import pandas as pd
naive = pd.Timestamp("2024-01-01")
aware = pd.Timestamp("2024-01-01", tz="UTC")
try:
naive < aware
except TypeError as e:
print(e) # Cannot compare tz-naive and tz-aware timestampsLocalize both sides the same way before comparing them.
Ambiguous and nonexistent local times
Some local readings are not valid instants. When clocks fall back, one hour occurs twice. When clocks spring forward, one hour never occurs. By default tz_localize raises an error for both cases. The ambiguous and nonexistent arguments let you choose a resolution.
import numpy as np
import pandas as pd
tz = "America/New_York"
# 2024-11-03 01:30 happens twice when clocks fall back
ambiguous = pd.DatetimeIndex(["2024-11-03 01:30"])
try:
ambiguous.tz_localize(tz)
except Exception as e:
print(type(e).__name__) # AmbiguousTimeError
print(ambiguous.tz_localize(tz, ambiguous=np.array([True]))) # first occurrence, -04:00
print(ambiguous.tz_localize(tz, ambiguous="NaT")) # NaT
# 2024-03-10 02:30 does not exist when clocks spring forward
missing = pd.DatetimeIndex(["2024-03-10 02:30"])
print(missing.tz_localize(tz, nonexistent="shift_forward")) # 2024-03-10 03:00:00-04:00For ambiguous, an array of booleans says whether each value falls in daylight saving time, so True picks the first occurrence. "NaT" marks ambiguous values as missing. For nonexistent, "shift_forward" moves the value to the first valid time after the gap.
Summary of the main points
tz_localizeattaches a zone and keeps the wall-clock reading.tz_convertchanges the displayed zone and keeps the instant.- Use IANA names so daylight saving rules apply.
- Use
.dt.tz_localizeon a Series, andtz_localizedirectly on an index or Timestamp.
Exercise
A Series holds naive values "2024-11-03 01:30" recorded in America/NewYork. You call s.dt.tzlocalize("America/New_York") and get an AmbiguousTimeError. Why does it happen, and how would you localize the value as the first occurrence?
Show answer
Clocks fall back on 2024-11-03, so 01:30 occurs twice in New York, and pandas cannot tell which one you mean. Pass ambiguous with a boolean array marking the value as daylight saving time, for example s.dt.tzlocalize("America/NewYork", ambiguous=np.array([True])). That picks the first occurrence at -04:00.
Exercise
You have a timestamp that already carries the zone UTC and you want it shown in Europe/Paris. Which method do you use, and why does tz_localize fail?
Show answer
Use tzconvert("Europe/Paris"). tzlocalize only attaches a zone to naive values, so on an aware value it raises a TypeError.