Sub topic 1
Naive and aware timestamps
Prerequisites
Assume you know basic Python, pandas Series and DataFrame objects, and the difference between a date, a clock time, and a duration.
A tz-naive timestamp has date and clock information but no time-zone rule. For example, 2024-03-10 12:00 could mean noon in New York, London, or Tokyo.
A tz-aware timestamp includes a time zone or UTC offset. It identifies an exact instant. pandas prevents direct comparisons between naive and aware timestamps because the meaning of the naive value is unknown.
import pandas as pd
naive = pd.Timestamp("2024-01-01 12:00")
aware = pd.Timestamp("2024-01-01 12:00", tz="UTC")
print(naive.tzinfo) # None
print(aware) # 2024-01-01 12:00:00+00:00
try:
print(naive < aware)
except TypeError as error:
print(type(error).__name__)UTC, offsets and IANA zone names
UTC is the common reference time, with an offset of +00:00. An offset is the difference between local clock time and UTC. For example, -05:00 means local time is five hours behind UTC.
An offset alone does not describe daylight saving rules. Prefer an IANA time-zone name, such as America/New_York or Europe/Berlin. An IANA name identifies a database entry containing historical and future clock rules. Its offset can change during the year.
Attaching a time zone with tz_localize
Use tz_localize when a timestamp contains local clock readings and you need to attach the correct zone. It keeps the wall-clock value unchanged while adding the zone.
Use the tz argument when creating an already aware timestamp. Do not use tz_localize to convert a timestamp that already has a time zone. Conversion uses tz_convert, covered later.
import pandas as pd
local_time = pd.Timestamp("2024-01-15 12:00")
new_york_time = local_time.tz_localize("America/New_York")
print(new_york_time)
# 2024-01-15 12:00:00-05:00
print(new_york_time.tz_convert("UTC"))
# 2024-01-15 17:00:00+00:00Exercise
What is the difference between tz_localize("UTC") and tz_convert("UTC")?
Show answer
tz_localize attaches UTC to a naive timestamp without changing its clock reading. tz_convert changes an already aware timestamp to UTC while preserving the same instant.