Sub topic 11
Removing Time Zones and Saving Data
This chapter covers what to do with tz-aware data when it leaves pandas. You will drop a time zone without corrupting the values. You will also learn which file formats keep zone information and which lose it, and how to write data so it can be read back correctly.
It assumes you can already use tz_localize and tz_convert on a Series or DatetimeIndex, and that you know the difference between naive and aware timestamps. It also assumes you know that an aware timestamp is an instant with an offset or zone attached.
Why you would remove a time zone
Staying tz-aware inside pandas is almost always the safer choice. Naive timestamps are the problem case, because they leave the zone implicit. You remove a zone for practical reasons:
- The destination cannot store zones. Excel is the common example.
- Another system expects a naive column, for example a database column of type
timestamp without time zone. - You need to compare against a naive column, and you have decided which zone that column is really in.
- You want local wall-clock features, such as "hour of day as a person saw it".
Removing a zone discards information, so the real question is which value you keep. A naive timestamp can hold either the local wall time or the UTC time. Pandas gives you one method for each.
Two ways to make a column naive
Two calls produce a naive result from an aware one. They give different answers.
tz_localize(None)removes the zone and keeps the local wall-clock reading.tz_convert(None)converts to UTC first, then removes the zone.
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")
print(s_ny.dt.tz_localize(None))
# 2024-01-15 09:30:00
# 2024-07-15 09:30:00
print(s_ny.dt.tz_convert(None))
# 2024-01-15 14:30:00
# 2024-07-15 13:30:00The first call keeps the clock reading you saw in New York. The second call keeps the UTC reading. Both outputs have dtype datetime64[ns] and no zone.
The method names read oddly here. tz_localize normally attaches a zone, and passing None is its way of detaching one. tz_convert(None) follows its usual meaning, which is to change the zone. Here the target is "no zone", reached through UTC.
I recommend writing the UTC version explicitly, so the intent is visible to readers:
import pandas as pd
def to_naive_utc(s: pd.Series) -> pd.Series:
"""Return the UTC wall-clock values of an aware Series, without a zone."""
if s.dt.tz is None:
raise ValueError("Series is already naive, so its zone is unknown")
return s.dt.tz_convert("UTC").dt.tz_localize(None)
s = pd.Series(pd.to_datetime(["2024-07-15 09:30"])).dt.tz_localize("America/New_York")
print(to_naive_utc(s)) # 2024-07-15 13:30:00The guard matters. Calling tz_convert on a naive Series raises a TypeError, because pandas will not guess a starting zone. Calling tz_localize(None) on a naive Series does nothing and raises no error, so a mistake there stays hidden. The helper turns that silent case into a loud one.
Choosing between the two
| Goal | Use | Result for 09:30 in New York in July |
|---|---|---|
| Keep a unique, ordered timeline | `tz_convert("UTC")` then `tz_localize(None)` | 13:30 |
| Show what a local person saw on their clock | `tz_localize(None)` | 09:30 |
| Hand data to a system that assumes UTC | `tz_convert(None)` | 13:30 |
| Hand data to a system that assumes local time | `tz_localize(None)` | 09:30 |
The deciding question is what the receiver will assume about the naive values. Document that assumption, preferably in the column name, for example created_utc.
What local wall time loses
The local version is lossy in a way the UTC version is not. During a fall-back DST change, one local hour happens twice. Two different instants then map to the same naive value.
import pandas as pd
utc = pd.date_range("2024-11-03 05:00", periods=3, freq="h", tz="UTC")
ny = utc.tz_convert("America/New_York")
print(ny)
# 01:00-04:00, 01:00-05:00, 02:00-05:00
local = ny.tz_localize(None)
print(local) # 01:00, 01:00, 02:00
print(local.is_unique) # FalseThe aware index has three distinct instants. The naive index has a duplicate. If that column is a key, it breaks uniqueness. If you sort by it, the order of the two 01:00 rows is arbitrary. Converting back to New York later raises an AmbiguousTimeError unless you pass ambiguous=, and by then you no longer know which of the two instants each row was.
The reverse also happens. A naive local column can contain a time such as 2024-03-10 02:30 that never existed in New York, and restoring the zone needs the nonexistent= argument. Both arguments are covered in the DST chapter. The practical lesson for this chapter is to avoid creating the problem. If the data will ever be put back on a timeline, strip the zone from UTC values, not from local ones.
Mixed zones in one column
A column holds one zone at a time. If you build a column from timestamps in different zones, pandas falls back to object dtype, which stores each element separately. The .dt accessor then fails. Normalize to UTC before doing anything else. Passing utc=True to pd.to_datetime does this at parse time, as in the chapter on parsing offsets:
import pandas as pd
raw = ["2024-01-01T00:00:00+01:00", "2024-06-01T00:00:00+02:00"]
col = pd.to_datetime(raw, utc=True)
print(col.tz) # UTCOnce the column is UTC, you can convert it to any display zone or strip the zone with tz_localize(None).
Saving data: what each format keeps
Formats differ in how they treat zones. The table summarizes the common ones when you write a tz-aware column with a recent pandas version.
| Format | Keeps the instant | Keeps the zone name | Notes |
|---|---|---|---|
| CSV | Yes, as text with an offset | No, only the offset | Reading back gives strings unless you parse them |
| Parquet (pyarrow) | Yes, stored as UTC | Yes | Reads back as a tz-aware dtype |
| Excel (`to_excel`) | Not accepted | Not applicable | Raises `ValueError` for aware datetimes |
| JSON | Depends on `date_format` | No | ISO format includes the offset |
CSV
CSV has no types, so everything is text. Pandas writes an aware timestamp with its offset. Reading it back produces strings. If the column spans a DST change, the offsets differ between rows, and a plain parse cannot form one dtype. This is why writing UTC is the dependable choice.
import io
import pandas as pd
df = pd.DataFrame({
"when": pd.date_range("2024-03-09 12:00", periods=3, freq="D", tz="America/New_York"),
"v": [1, 2, 3],
})
out = df.assign(when=df["when"].dt.tz_convert("UTC"))
buf = io.StringIO()
out.to_csv(buf, index=False)
print(buf.getvalue())
# when,v
# 2024-03-09 17:00:00+00:00,1
# 2024-03-10 16:00:00+00:00,2
# 2024-03-11 16:00:00+00:00,3
buf.seek(0)
back = pd.read_csv(buf)
print(back["when"].dtype) # strings, not datetimes
back["when"] = pd.to_datetime(back["when"], utc=True)
print(back["when"].dtype) # datetime64[ns, UTC] (the unit can differ in newer pandas)
back["when"] = back["when"].dt.tz_convert("America/New_York")
print(back["when"].iloc[0]) # 2024-03-09 12:00:00-05:00The local noon values are 17:00 UTC before the change and 16:00 UTC after it, because the New York offset moved from -05:00 to -04:00. After the round trip, the instants are identical to the originals. The zone name is restored by an explicit tz_convert, since a CSV file cannot carry it.
Always pass utc=True when parsing a column like this. Without it, pandas may return object dtype for mixed offsets, which breaks .dt.
Parquet
Parquet is typed, so it does better. With pyarrow installed, an aware column is stored as UTC instants plus the zone label, and reading it back restores the dtype.
import io
import pandas as pd
df = pd.DataFrame({
"when": pd.date_range("2024-03-09 12:00", periods=3, freq="D", tz="America/New_York"),
"v": [1, 2, 3],
})
buf = io.BytesIO()
df.to_parquet(buf) # requires pyarrow
buf.seek(0)
back = pd.read_parquet(buf)
print(back["when"].dtype) # datetime64[..., America/New_York]
print(back["when"].equals(df["when"])) # TrueIf you control both ends of the pipeline, Parquet with aware columns removes most of the work in this chapter. Check that downstream readers support timestamps with zones. Some engines ignore the label and show UTC.
Excel
Excel cells hold no zone. Calling to_excel on a DataFrame with an aware datetime column raises a ValueError that asks you to make the datetimes timezone unaware. Choose the naive form deliberately. For a report read by people in one office, use tz_localize(None) on the local column. For data that another program will process, use to_naive_utc. Either way, say which one you chose in the column header.
Keeping the zone when the format cannot
Sometimes you need a naive column and the ability to restore the local view. Save the UTC value plus the zone name as a separate column, then rebuild:
import pandas as pd
stored = pd.DataFrame({
"when_utc": pd.to_datetime(["2024-03-09 17:00", "2024-03-10 16:00"]),
"zone": ["America/New_York", "America/New_York"],
})
restored = stored["when_utc"].dt.tz_localize("UTC").dt.tz_convert("America/New_York")
print(restored)
# 2024-03-09 12:00:00-05:00
# 2024-03-10 12:00:00-04:00The rule behind this pattern is that UTC identifies the instant and the zone name says how to display it. A fixed offset such as -05:00 does not work as a replacement for the zone name. It describes only one moment and gives the wrong local time for dates after the next DST change.
If the data has different zones per row, for example one per customer, restore each group separately with groupby("zone") and convert within each group. A single column can only hold one zone.
A decision path
Common errors
- Using
tz_localize(None)when you wanted UTC. The values look plausible but are off by the zone's offset. Check one row by hand against a known time. - Assuming CSV round-trips the dtype. It does not. Parse with
pd.to_datetime(..., utc=True)and convert to the display zone afterward. - Calling
tz_convert(None)on a naive column. It raisesTypeError. Localize first, and only if you know the real zone. - Stripping the zone before a DST-sensitive operation. Do resampling and day-boundary logic while the data is still aware, and strip the zone last.
- Treating an offset as a zone. Saving
-05:00does not tell you whether July values were in daylight time. Save the IANA name or save UTC.
Exercise
Given idx = pd.DatetimeIndex(["2024-07-01 08:00"]).tzlocalize("Europe/Berlin"), what do idx.tzlocalize(None) and idx.tz_convert(None) return, and which would you use to write a column for a system that assumes UTC?
Show answer
idx.tzlocalize(None) returns 2024-07-01 08:00 because it keeps the local wall-clock reading. idx.tzconvert(None) returns 2024-07-01 06:00 because Berlin is at UTC+02:00 in July, so the UTC reading is two hours earlier. For a system that assumes UTC, use tzconvert(None), or the more explicit tzconvert("UTC") followed by tz_localize(None).
Exercise
A New York column covers 2024-11-03 and you convert it with tz_localize(None). Why can the resulting column no longer be used as a unique key, and what should you have stripped the zone from instead?
Show answer
The local hour 01:00 to 02:00 occurs twice on that date, once at -04:00 and once at -05:00. Removing the zone keeps only the wall-clock reading, so the two distinct instants become the same naive value. Convert to UTC first with tzconvert("UTC") and then call tzlocalize(None), since UTC has no repeated hours.