Sub topic 7
Comparing and Subtracting Aware Timestamps
This chapter assumes you can already attach a zone with tz_localize, change it with tz_convert, and recognize a tz-aware dtype such as datetime64[ns, America/New_York]. Here you will see how pandas compares and subtracts timestamps once zones are involved. The rule is simple, but its consequences surprise people around daylight saving time (DST) and when naive and aware values meet.
Comparisons look at the instant
An aware timestamp stores one moment on the UTC timeline plus a zone used for display. When you compare two aware timestamps, pandas compares the moments. The zone each one is displayed in does not matter.
import pandas as pd
ny = pd.Timestamp("2024-03-10 08:00", tz="America/New_York")
utc = pd.Timestamp("2024-03-10 12:00", tz="UTC")
tokyo = pd.Timestamp("2024-03-10 21:00", tz="Asia/Tokyo")
print(ny == utc) # True: both are 12:00 UTC
print(utc == tokyo) # True: Tokyo is UTC+9, so 21:00 is 12:00 UTC
later = pd.Timestamp("2024-03-10 08:30", tz="UTC")
print(ny > later) # True, although the wall clock 08:00 looks earlier than 08:30The last line shows why you should not read wall-clock digits when comparing across zones. ny shows 08:00, but that is 12:00 UTC, which is after 08:30 UTC.
Two values can be equal and still carry different zones. If you need to know which zone a value is in, check ts.tz. Do not rely on equality.
Mixing naive and aware values
A naive timestamp has no zone, so pandas cannot place it on the UTC timeline. It refuses to guess. The behavior depends on the operation.
import pandas as pd
naive = pd.Timestamp("2024-01-01")
aware = pd.Timestamp("2024-01-01", tz="UTC")
print(naive == aware) # False: equality quietly reports "not equal"
try:
naive < aware
except TypeError as e:
print(e) # Cannot compare tz-naive and tz-aware timestamps
try:
aware - naive
except TypeError as e:
print("subtraction:", type(e).__name__) # subtraction: TypeError| Operation | Naive with aware | Aware with aware |
|---|---|---|
| `==` | `False`, no error | Compares instants |
| `<`, `>`, `<=`, `>=` | `TypeError` | Compares instants |
| `-` | `TypeError` | `Timedelta` of elapsed time |
The quiet False from == is the more dangerous behavior. A filter such as df["ts"] == some_value can return no rows with no error, because one side was naive. If a comparison returns nothing, check .dt.tz on the column and .tz on the value.
There are two ways to fix a mix:
- Localize the naive side, once you know which zone it really represents.
- Use a zone-aware constructor for "now", such as
pd.Timestamp.now(tz="UTC"). A plainpd.Timestamp.now()is naive and fails against aware data.
import pandas as pd
naive = pd.Timestamp("2024-01-01")
aware = pd.Timestamp("2024-01-01", tz="UTC")
print(naive.tz_localize("UTC") == aware) # True
print(naive.tz_localize("UTC") < aware) # False
now = pd.Timestamp.now(tz="UTC")
print(now > aware) # TrueLocalizing a naive value is a claim about where that value came from. If a server log was written in Europe/Berlin and you localize it to UTC, every comparison will be off by one or two hours, and no error will warn you. Choose the zone from knowledge of the data source.
Subtraction measures elapsed time
Subtracting two aware timestamps gives a Timedelta. It is the real time between the two instants, whatever zones the values are displayed in. This works for scalars, and it works between two datetime columns even when the columns have different zones.
import pandas as pd
trips = pd.DataFrame({
"depart": pd.DatetimeIndex(
["2024-03-09 22:00", "2024-03-10 04:00"]
).tz_localize("America/New_York"),
"arrive": pd.DatetimeIndex(
["2024-03-10 11:00", "2024-03-10 15:00"]
).tz_localize("Europe/London"),
})
trips["elapsed"] = trips["arrive"] - trips["depart"]
trips["hours"] = trips["elapsed"].dt.total_seconds() / 3600
trips["wall_clock"] = (
trips["arrive"].dt.tz_localize(None) - trips["depart"].dt.tz_localize(None)
)
print(trips[["elapsed", "hours", "wall_clock"]])
# elapsed: 8 hours and 7 hours
# hours: 8.0 and 7.0
# wall_clock: 13 hours and 11 hoursEach row is a flight that leaves New York and lands in London. In the first row, 22:00 in New York on March 9 is 03:00 UTC on March 10. The arrival at 11:00 in London is 11:00 UTC. The flight lasted 8 hours.
The wall_clock column shows the mistake to avoid. tz_localize(None) drops the zone and keeps the local digits. Subtracting those digits gives 13 hours and 11 hours, which ignore the zone difference. Use tz_localize(None) only when you want local-clock arithmetic, as in "how late in the local day did this happen".
Notice the second row. New York switches to daylight time at 02:00 on March 10, so 04:00 that morning is already -04:00. tz_localize handled that shift for you.
Both columns had to be aware. Had one been naive, the subtraction would have raised TypeError.
Elapsed time across a DST change
Elapsed time between two local midnights is not always 24 hours. When clocks change, one calendar day is 23 or 25 hours long, and subtraction reports that exactly.
import pandas as pd
tz = "America/New_York"
spring = pd.Timestamp("2024-03-11", tz=tz) - pd.Timestamp("2024-03-10", tz=tz)
fall = pd.Timestamp("2024-11-04", tz=tz) - pd.Timestamp("2024-11-03", tz=tz)
normal = pd.Timestamp("2024-06-02", tz=tz) - pd.Timestamp("2024-06-01", tz=tz)
print(spring) # 0 days 23:00:00
print(fall) # 1 days 01:00:00
print(normal) # 1 days 00:00:00On March 10, 2024, the clock jumps from 02:00 to 03:00, so that day has 23 hours. On November 3, 2024, the hour from 01:00 to 02:00 happens twice, so that day has 25 hours.
The diagram summarizes how pandas decides what a subtraction means.
The naive branch has the same trap in reverse. Two naive timestamps that straddle a DST change are subtracted as plain digits, so the result can be an hour off from the real elapsed time. Naive data hides the 23-hour and 25-hour days.
Adding durations: fixed time versus calendar steps
Subtraction produces a Timedelta, and addition of a Timedelta is the reverse operation. A Timedelta is a fixed length of time. pd.Timedelta(days=1) means exactly 24 hours. A DateOffset moves by calendar units.
import pandas as pd
tz = "America/New_York"
start = pd.Timestamp("2024-03-10 00:00", tz=tz)
print(start + pd.Timedelta(hours=24)) # 2024-03-11 01:00:00-04:00
print(start + pd.Timedelta(days=1)) # 2024-03-11 01:00:00-04:00
print(start + pd.DateOffset(days=1)) # 2024-03-11 00:00:00-04:00The Timedelta versions land at 01:00 because 24 real hours passed and one local hour was skipped. The DateOffset keeps the local time and lands at midnight. The two results are 23 hours apart. The chapter on calendar days versus 24-hour steps covers how this affects date_range. For now, remember that "plus one day" has two meanings, and you must choose one.
Comparing columns and filtering
Comparisons on a Series work element by element and follow the same rules. A tz-aware Series can be compared with an aware scalar in any zone.
import pandas as pd
s = pd.Series(
pd.to_datetime(["2024-01-01 20:00", "2024-01-02 02:00"])
).dt.tz_localize("America/New_York")
cutoff_utc = pd.Timestamp("2024-01-02 03:00", tz="UTC")
print((s >= cutoff_utc).tolist()) # [False, True]
print((s >= "2024-01-02 03:00").tolist()) # [False, False]The first comparison uses an aware cutoff. The values are 01:00 UTC and 07:00 UTC on January 2, so only the second reaches 03:00 UTC.
The second comparison uses a bare string. pandas parses the string in the Series' own zone, so the cutoff becomes 03:00 in New York, which is 08:00 UTC. Neither value reaches it. The same text gave a different answer because it was read in a different zone. When a filter's meaning depends on a zone, pass an aware Timestamp so the code states which zone is intended.
Filtering on elapsed time uses Timedelta comparisons:
import pandas as pd
trips = pd.DataFrame({
"depart": pd.DatetimeIndex(
["2024-03-09 22:00", "2024-03-10 04:00"]
).tz_localize("America/New_York"),
"arrive": pd.DatetimeIndex(
["2024-03-10 11:00", "2024-03-10 15:00"]
).tz_localize("Europe/London"),
})
trips["elapsed"] = trips["arrive"] - trips["depart"]
long_trips = trips[trips["elapsed"] > pd.Timedelta(hours=7, minutes=30)]
print(len(long_trips)) # 1Other things to watch for
- Mixed zones in one column. A single column cannot hold values with different zones in the tz-aware dtype. pandas falls back to
objectdtype, and comparisons then run slowly, one Python object at a time. Convert the column to one zone, or to UTC, before comparing. Parsing withutc=Truedoes this at read time. - Missing values.
NaThas no zone and does not cause a naive-versus-aware error. Comparisons that involveNaTreturnFalse, and subtracting it givesNaT. - Sorting and min/max. These use the same instant ordering, so
s.min()ands.sort_values()work on a single-zone aware column without conversion. - Wall-clock fields. Attributes such as
.dt.hourand.dt.datereport local values in the column's zone. Two equal instants shown in different zones have different.hourvalues. - Which zone to choose. For storing and comparing, UTC is the safe default. Convert to a local zone for display or for local-day logic.
Exercise
A DataFrame column start is tz-aware in America/New_York, and a column end is tz-aware in Asia/Tokyo. A teammate writes df["end"].dt.tz_localize(None) - df["start"].dt.tz_localize(None) to get the duration. What does this compute, and what is the correct expression?
Show answer
It subtracts the local wall-clock digits and ignores the 13 or 14 hour zone difference, so the result is wrong for real duration. The correct expression is df["end"] - df["start"], which compares the instants on the UTC timeline and returns the elapsed time.
Exercise
What do pd.Timestamp("2024-11-03", tz="America/New_York") and pd.Timestamp("2024-11-04", tz="America/New_York") give when you subtract the first from the second, and why is the answer not exactly one day?
Show answer
The result is Timedelta('1 days 01:00:00'), which is 25 hours. Clocks in New York fall back from 02:00 to 01:00 on November 3, 2024, so that local day has an extra hour. Subtraction of aware timestamps reports real elapsed time, not the number of calendar days.