Sub topic 11
Removing time zones and saving data
This chapter assumes you can attach and convert zones with tz_localize and tz_convert, and that you know the .dt accessor. It covers how to drop a time zone safely and how tz-aware data behaves when you write it to files.
Two ways to drop a zone
Passing None to either method returns a tz-naive result. The two methods keep different clock times.
tz_localize(None)removes the zone and keeps the local wall-clock time.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")
local_naive = s_ny.dt.tz_localize(None)
utc_naive = s_ny.dt.tz_convert(None)
print(local_naive) # 09:30 and 09:30, the local clock readings
print(utc_naive) # 14:30 and 13:30, the UTC clock readingsBoth results have dtype datetime64[ns] and no zone information. Nothing in the data records which choice you made.
Choosing what to keep
The right choice depends on what the naive value means to its reader.
| Goal | Call | Result |
|---|---|---|
| Store a precise instant in a system that has no zone support | `tz_convert(None)` | UTC wall-clock time |
| Show "what the clock on the wall said" | `tz_localize(None)` | Local wall-clock time |
For storage, UTC is the safer choice. Local wall-clock values cannot be turned back into instants without knowing the zone. They are also ambiguous during the hour when clocks fall back.
Saving to CSV
CSV stores text, so pandas writes the UTC offset into each value. Reading it back with parse_dates restores an aware column when every row has the same offset.
import io
import pandas as pd
s = pd.Series(pd.to_datetime(["2024-01-15 09:30", "2024-07-15 09:30"]))
df = pd.DataFrame({
"when": s.dt.tz_localize("America/New_York").dt.tz_convert("UTC"),
"value": [1, 2],
})
text = df.to_csv(index=False)
print(text)
# when,value
# 2024-01-15 14:30:00+00:00,1
# 2024-07-15 13:30:00+00:00,2
back = pd.read_csv(io.StringIO(text), parse_dates=["when"])
print(back["when"].dtype) # tz-aware, with UTC as the zoneSaving UTC first matters. If you wrote New York values directly, the file would contain -05:00 and -04:00 offsets. On reading, pandas cannot build one tz-aware column from rows with different offsets. It returns an object column of Python datetimes. The fix is the one from the parsing chapter:
back["when"] = pd.to_datetime(back["when"], utc=True)After that, convert to a named zone with tz_convert if you need local display. The offset in the file never recovers the zone name, because an offset such as -05:00 does not tell you which region produced it.
Other formats
- Parquet stores the zone with the column. A tz-aware column read back from Parquet keeps its dtype and zone name. This needs
pyarroworfastparquetinstalled. - Excel cannot hold time zones.
to_excelraises aValueErrorfor tz-aware columns, so remove the zone first. - Databases vary. Many have a "timestamp without time zone" type that behaves like a naive column. Convert to UTC before writing and agree on that convention with the readers.
For Excel, a safe pattern is:
out = df.copy()
out["when"] = out["when"].dt.tz_convert("America/New_York").dt.tz_localize(None)
out = out.rename(columns={"when": "when_new_york_local"})The new column name documents the meaning of the naive values. That is the main defence against someone later treating them as UTC.
Common mistakes
- Calling
tz_localize(None)on UTC data and assuming nothing changed. It is only harmless if UTC is the convention you want. - Using
tz_localize("UTC")on a column that already has a zone. That raises aTypeError. Usetz_convertfor aware data. - Dropping the zone and then comparing against aware timestamps. This raises the naive-versus-aware
TypeErrorfrom earlier chapters.
Exercise
A DataFrame column ts is tz-aware in Europe/Berlin. You must write it to a system that only accepts naive timestamps and must always be read as UTC. Which single expression produces the right column, and why not tz_localize(None)?
Show answer
Use df["ts"].dt.tz_convert(None). It converts each instant to UTC and then removes the zone, so the naive values are UTC clock times. tz_localize(None) would keep the Berlin wall-clock time, which is one or two hours ahead of UTC depending on DST. A reader who assumes UTC would then be off by that amount.