Sub topic 2
Measuring Durations with Timedelta
Assume you know basic pandas Series and DataFrame creation, column selection, and boolean filtering. This chapter uses timestamps, which represent points in time, and Timedelta, which represents a duration between points.
Measuring durations with `Timedelta`
Subtracting two pandas timestamps produces a Timedelta. Use .dt.total_seconds() or related methods to convert durations into numeric units.
import pandas as pd
df = pd.DataFrame({
"when": pd.to_datetime([
"2024-03-01 09:30",
"2024-03-01 11:00",
"2024-03-01 15:15",
]),
"amount": [10, 25, 40],
})
df["elapsed"] = df["when"].diff()
df["elapsed_hours"] = df["elapsed"].dt.total_seconds() / 3600
print(df)The first difference is NaT because there is no earlier timestamp. NaT means “Not a Time” and represents a missing or invalid time value.
Indexing and slicing with a `DatetimeIndex`
A DatetimeIndex lets pandas use dates for selection and slicing. Sort the index first so range selections behave predictably.
ts = (
df.set_index("when")["amount"]
.sort_index()
)
print(ts.loc["2024-03-01 11:00"])
print(ts.loc["2024-03-01 09:30":"2024-03-01 12:00"])
print(ts.loc["2024-03-01"]) # all rows on this datePartial date strings work when the index contains datetime values. They are interpreted as time ranges, not ordinary text.
Building regular time axes with `date_range`
pd.date_range() creates evenly spaced timestamps. This is useful for constructing an expected schedule or an empty time axis.
days = pd.date_range("2024-01-01", periods=5, freq="D")
values = pd.Series(range(5), index=days)
print(values)Frequency aliases and date offsets
A frequency alias is a short code describing a time interval.
| Alias | Meaning |
|---|---|
| `D` | calendar day |
| `h` | hour |
| `W` | week |
| `B` | business day |
Use offsets such as pd.offsets.MonthEnd() when calendar rules matter.
print(pd.date_range("2024-01-01", periods=4, freq="B"))
stamp = pd.Timestamp("2024-01-15")
print(stamp + pd.offsets.MonthEnd())Exercise
What does df["when"].diff() return for the first row?
Show answer
It returns NaT because the first row has no preceding timestamp.