Sub topic 4
Converting between zones with tz_convert
This chapter assumes you can already create tz-aware data with tz_localize, and that you know what UTC, offsets and IANA zone names such as America/New_York are. If a timestamp's tzinfo still looks mysterious, review the earlier chapters on naive versus aware timestamps and on localizing.
tz_convert changes how an instant is displayed. It never changes which instant it is. This chapter covers that model, how it works on each pandas container, and the mistakes that come up in practice.
The working model
An aware timestamp stores two things: a point on the UTC timeline, and a zone used to display it as a wall-clock time. tz_convert keeps the first and swaps the second. Both timestamps below are the same moment, so they compare equal.
import pandas as pd
ts = pd.Timestamp("2024-07-01 12:00", tz="UTC")
print(ts.tz_convert("Europe/Berlin")) # 2024-07-01 14:00:00+02:00
print(ts.tz_convert("Asia/Kolkata")) # 2024-07-01 17:30:00+05:30
print(ts.tz_convert("Australia/Sydney")) # 2024-07-01 22:00:00+10:00
print(ts == ts.tz_convert("Asia/Kolkata")) # TrueThe offsets differ for each zone, and each zone's rules decide the offset in effect on that date. Berlin is on summer time in July, so it is UTC+2. Sydney is in its winter, so it is UTC+10 rather than UTC+11.
tz_localize versus tz_convert
The two methods are easy to confuse. Use this table to pick one.
| Question | `tz_localize` | `tz_convert` |
|---|---|---|
| Input must be | naive | aware |
| What it changes | attaches a zone and keeps the wall-clock digits | changes the zone and keeps the instant |
| Does the UTC instant change? | yes, it is determined by the zone you attach | no |
| Can it hit DST ambiguity? | yes | no |
| Passing `None` | drops the zone, keeps wall-clock digits | converts to UTC, then drops the zone |
The "DST ambiguity" row matters in practice. Converting from an aware timestamp is always well defined, because the instant is known. Ambiguous and nonexistent local times only appear when you go from naive to aware. That is why the DST arguments (ambiguous, nonexistent) belong to tz_localize, not tz_convert.
Converting each container
tz_convert is available in three places, and the signature is the same idea each time.
Timestamp.tz_convert(tz)for a single value.DatetimeIndex.tz_convert(tz)for an index.Series.dt.tz_convert(tz)for a datetime column.
Converting a DatetimeIndex is the same call. The example below uses hourly UTC data that crosses the US spring-forward change at 07:00 UTC on 2024-03-10.
import pandas as pd
idx = pd.date_range("2024-03-10 04:00", periods=4, freq="h", tz="UTC")
ny = idx.tz_convert("America/New_York")
print(ny.strftime("%H:%M %z").tolist())
# ['23:00 -0500', '00:00 -0500', '01:00 -0500', '03:00 -0400']The four UTC hours are evenly spaced, but the local clock jumps from 01:00 to 03:00. The offset changes from -0500 to -0400 on its own. You did not handle the DST change. The zone's rules did it, and this is the main reason to keep data in UTC and convert only for display.
Series and DataFrame columns
A datetime column needs the .dt accessor. A common pattern is to store one UTC column and derive a local column per audience.
import pandas as pd
df = pd.DataFrame({
"event_utc": pd.to_datetime(
["2024-03-31 00:30", "2024-03-31 01:30"], utc=True
)
})
df["london"] = df["event_utc"].dt.tz_convert("Europe/London")
df["berlin"] = df["event_utc"].dt.tz_convert("Europe/Berlin")
print(df["london"].dt.strftime("%H:%M %z").tolist()) # ['00:30 +0000', '02:30 +0100']
print(df["berlin"].dt.strftime("%H:%M %z").tolist()) # ['01:30 +0100', '03:30 +0200']Both zones change to summer time at 01:00 UTC on that date. The two events fall on either side of that moment, so each zone shows an offset change between them. The UTC column is untouched, and each new column has a dtype like datetime64[ns, Europe/London].
If the timestamps are the index of a DataFrame or Series, you can call df.tz_convert(zone) directly. It converts the index. For a MultiIndex, pass level= to choose which level to convert.
import pandas as pd
df = pd.DataFrame(
{"value": [1, 2]},
index=pd.date_range("2024-01-01", periods=2, freq="12h", tz="UTC"),
)
df_ny = df.tz_convert("America/New_York")
print(df_ny.index.strftime("%Y-%m-%d %H:%M").tolist())
# ['2023-12-31 19:00', '2024-01-01 07:00']Notice that the first row now belongs to 31 December in local time. Any grouping or .dt.date call on the converted data uses the local date, not the UTC date.
Removing the zone during conversion
Passing None to tz_convert converts to UTC first and then removes the zone. Passing None to tz_localize removes the zone but keeps the local wall-clock digits. The results differ whenever the zone is not UTC.
import pandas as pd
ts = pd.Timestamp("2024-01-15 09:30", tz="America/New_York")
print(ts.tz_convert(None)) # 2024-01-15 14:30:00 (UTC digits, naive)
print(ts.tz_localize(None)) # 2024-01-15 09:30:00 (local digits, naive)Pick based on what the naive result will mean later. A naive column of UTC values should be documented as UTC. A naive column of local values loses information on the repeated hour after a fall-back change, because two different instants share the same digits.
Zone arguments
The tz argument accepts several forms.
- An IANA name string, such as
"America/New_York". This follows DST rules. "UTC"ordatetime.timezone.utc.- A fixed-offset
datetime.timezone, such astimezone(timedelta(hours=5, minutes=30)). This has no DST rules, so its offset never changes. - A tzinfo object from your time zone backend (
zoneinfo,pytzordateutil).
Prefer IANA names for any real location. A fixed offset such as -05:00 describes New York only in winter, so converting to it gives the wrong wall-clock time for half the year. A misspelled zone name raises an error that names the unknown zone, so typos fail early.
Common errors
Converting naive data
tz_convert refuses naive input. pandas does not guess which zone the digits belong to.
import pandas as pd
s = pd.Series(pd.to_datetime(["2024-01-15 09:30"])) # naive
try:
s.dt.tz_convert("UTC")
except TypeError as e:
print(type(e).__name__) # TypeError
fixed = s.dt.tz_localize("America/New_York").dt.tz_convert("UTC")
print(fixed.dt.strftime("%H:%M").tolist()) # ['14:30']The fix is to localize first, using the zone the data was recorded in, and then convert. If you do not know the recording zone, that is a data-quality problem and no method can solve it for you.
Localizing when you meant to convert
Calling tz_localize("UTC") on a column that is already aware raises an error. Calling it on a naive column that actually holds local times silently produces wrong instants, with no error. Before you convert, check s.dt.tz. It is None for naive data and a zone object for aware data.
Expecting the original column to change
tz_convert returns a new object. Writing df["ts"].dt.tz_convert("UTC") without assigning the result changes nothing.
Mixed zones in one column
A column cannot hold two zones in a proper datetime dtype. If a parse leaves you with object dtype containing mixed offsets, .dt is unavailable. Re-parse with pd.to_datetime(..., utc=True) and then convert, as covered in the parsing chapter.
Grouping by the wrong day
After converting, local midnight is the day boundary. A daily count on UTC data and a daily count on converted data can assign the same event to different dates. Decide which calendar your report should use, and convert before extracting dates.
A reliable workflow
- Store and process instants in UTC.
- Check that a column is aware (
.dt.tz is not None) before converting. - Convert to a local zone as late as possible, usually only for display, daily grouping, or business-hour filters.
- Use IANA names, not fixed offsets, for places that observe DST.
- When you need naive output, choose
tz_convert(None)for UTC digits ortz_localize(None)for local digits, and record which one you used.
Exercise
A Series s holds naive timestamps that were recorded in Asia/Tokyo local time. Write the one expression that gives the same instants as a UTC-aware Series. Then say what happens if you skip the first step and call only s.dt.tz_convert("UTC").
Show answer
s.dt.tz_localize("Asia/Tokyo").dt.tz_convert("UTC"). Skipping the localize step raises a TypeError, because tz_convert does not accept naive timestamps and pandas will not guess the zone.
Exercise
ts = pd.Timestamp("2024-01-15 09:30", tz="America/New_York"). What does ts.tz_convert("UTC").hour return, and is ts.tz_convert("UTC") == ts true or false?
Show answer
The hour is 14, because New York is UTC-5 in January. The comparison is True, because both timestamps are the same instant and only the displayed zone differs.
Exercise
An aware column in UTC has a value of 2024-01-01 03:00. After .dt.tz_convert("America/New_York"), what date does .dt.date report for that row, and why might this surprise someone who grouped by date before converting?
Show answer
It reports 2023-12-31, because the local time is 22:00 on the previous day (UTC-5). Grouping by date before converting would put this event in 1 January, so the two groupings disagree.