Sub topic 7
Comparing and subtracting aware timestamps
This chapter assumes you can create tz-aware timestamps with tz_localize and convert them with tz_convert. It also assumes you know what Timedelta is. Here you will see how pandas compares and subtracts aware values, and which mistakes raise errors or give surprising results.
Aware values compare by instant
An aware timestamp stores one instant on the UTC timeline and displays it in a zone. A comparison looks at the instant and ignores the display zone. Two timestamps in different zones are equal when they name the same moment.
import pandas as pd
utc = pd.Timestamp("2024-03-10 12:00", tz="UTC")
ny = pd.Timestamp("2024-03-10 08:00", tz="America/New_York")
print(utc == ny) # True, 08:00 in New York is -04:00 on this date
print(utc < ny.tz_convert("Asia/Tokyo")) # False, same instant
print(utc - ny) # 0 days 00:00:00You do not need to convert both sides to one zone before comparing. Convert only when you want to display or group by a particular zone.
Mixing naive and aware fails
A naive timestamp has no instant, because the zone is missing. pandas refuses to guess one. Ordering comparisons and subtraction raise TypeError. Equality is the exception: == quietly returns False.
import pandas as pd
naive = pd.Timestamp("2024-01-01")
aware = pd.Timestamp("2024-01-01", tz="UTC")
print(naive == aware) # False, no error
for op in (lambda: naive < aware, lambda: aware - naive):
try:
op()
except TypeError as e:
print(type(e).__name__, e)The silent False from == is a common source of bugs. A filter such as df["ts"] == some_timestamp returns no rows and no warning when one side is naive. If a comparison unexpectedly matches nothing, check .dt.tz or .tzinfo on both sides first.
To fix a mismatch, localize the naive side with tz_localize. Pick the zone the data was recorded in. Do not pick one only because it makes the error go away.
Subtraction measures elapsed time
Subtracting two aware timestamps gives a Timedelta of real elapsed time. This matters across daylight saving time (DST), where the wall-clock gap and the elapsed gap differ.
import pandas as pd
tz = "America/New_York"
start = pd.Series(pd.to_datetime(["2024-03-10 00:00", "2024-11-03 00:00"])).dt.tz_localize(tz)
end = pd.Series(pd.to_datetime(["2024-03-10 06:00", "2024-11-03 06:00"])).dt.tz_localize(tz)
print(end - start)
# 0 0 days 05:00:00
# 1 0 days 07:00:00Both rows show a six-hour wall-clock gap. In March the clocks skip an hour, so only five hours pass. In November the clocks repeat an hour, so seven hours pass. If you need the elapsed time, this result is correct. If you need the wall-clock gap, subtract the naive values instead.
Comparing columns and constants
Comparison operators work element by element on aware Series, with either another Series or a single Timestamp. Zones may differ between the two sides.
import pandas as pd
s = pd.Series(pd.to_datetime(["2024-01-01 00:00", "2024-06-01 00:00"])).dt.tz_localize("UTC")
cutoff = pd.Timestamp("2024-03-01", tz="America/New_York")
print(s > cutoff)
# 0 False
# 1 True
print(s[s > cutoff])The cutoff is midnight in New York, which is 05:00 UTC. The mask uses that instant. A cutoff written as a plain string in a comparison is parsed in the Series' own zone. Use an explicit aware Timestamp when the zone matters.
Adding durations
Adding a Timedelta moves along the UTC timeline by an exact amount. Adding a DateOffset with days moves by calendar days in local time. The two differ across a DST change.
import pandas as pd
t = pd.Timestamp("2024-03-09 12:00", tz="America/New_York")
print(t + pd.Timedelta(hours=24)) # 2024-03-10 13:00:00-04:00
print(t + pd.DateOffset(days=1)) # 2024-03-10 12:00:00-04:00The next chapter builds on this distinction for ranges. For now, remember that Timedelta arithmetic is elapsed time and DateOffset arithmetic is local calendar time.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError` on `<` or `-` | One side is naive | `tz_localize` the naive side |
| Filter with `==` returns nothing | Naive and aware values never match | Check `.dt.tz` on both sides |
| Duration off by one hour | Subtracted naive wall-clock values across DST | Subtract aware values |
| Result looks shifted by zone offset | Naive side localized to the wrong zone | Localize to the zone of origin |
Exercise
A DataFrame has a naive column login and an aware column logout in UTC. The login times were recorded in Europe/Berlin. Write the expression for session length, and say why df["logout"] - df["login"] fails.
Show answer
df["logout"] - df["login"].dt.tz_localize("Europe/Berlin"). The plain subtraction raises TypeError because a naive value has no instant, so pandas cannot subtract it from an aware one. Localizing login to the zone where it was recorded gives both columns an instant, and the result is a Timedelta of elapsed time.