Sub topic 5
Measuring durations with Timedelta
A Timedelta is a fixed length of time, such as 2 days and 5 hours. This chapter covers how to create one, where it comes from, and how to use it in calculations. It assumes you can create DataFrames, select columns, filter rows with boolean masks, and convert text to datetimes with pd.to_datetime.
Where Timedeltas come from
Subtracting one Timestamp from another gives a Timedelta. Adding a Timedelta to a Timestamp gives a new Timestamp.
import pandas as pd
start = pd.Timestamp("2024-03-01 09:30")
end = pd.Timestamp("2024-03-03 14:45")
gap = end - start
print(gap)
print(type(gap))
print(gap.days, gap.seconds)
print(gap.total_seconds() / 3600)The gap is 2 days and 5 hours 15 minutes. gap.days is 2 and gap.seconds is 18900. The last line prints 53.25 hours.
Creating Timedeltas directly
You can build a Timedelta from keyword arguments or from a string. pd.to_timedelta does the same for whole lists and Series.
print(pd.Timedelta(days=1, hours=6))
print(pd.Timedelta("90min"))
print(pd.to_timedelta([1, 2, 3], unit="h"))Durations in a DataFrame
Subtracting two datetime columns gives a column with a timedelta64 dtype. That dtype has its own .dt accessor.
df = pd.DataFrame({
"start": pd.to_datetime(["2024-03-01 09:30", "2024-03-02 14:45", "2024-03-05 08:00"]),
"end": pd.to_datetime(["2024-03-01 11:00", "2024-03-02 18:15", "2024-03-06 08:00"]),
})
df["duration"] = df["end"] - df["start"]
df["hours"] = df["duration"].dt.total_seconds() / 3600
print(df["hours"].tolist())
print(df["duration"].mean())
print(df["duration"].max())The hours are [1.5, 3.5, 24.0]. The mean duration is 0 days 09:40:00. Aggregations such as sum, mean, min, and max work on Timedelta columns and return Timedeltas.
Comparing and converting durations
Compare a Timedelta column with a Timedelta value to filter rows. Divide by a Timedelta to express durations in any unit as a float.
long_jobs = df[df["duration"] > pd.Timedelta(hours=2)]
print(long_jobs[["start", "duration"]])
df["days"] = df["duration"] / pd.Timedelta(days=1)
df["due"] = df["start"] + pd.Timedelta(days=2, hours=12)
print(df[["days", "due"]])Dividing by pd.Timedelta(hours=1) is an alternative to total_seconds() / 3600. It lets you choose the unit without remembering a conversion factor.
Timedelta components versus totals
The .dt accessor on a Timedelta column exposes days, seconds, and microseconds. These are components, not totals. A 2-day, 5-hour gap has days == 2 and seconds == 18000, so seconds ignores the days.
Timedeltas also cannot represent months or years, because those have no fixed length. pd.Timedelta(months=1) raises an error. For calendar-aware shifts, use pd.DateOffset(months=1), which is covered in the chapter on frequency aliases and date offsets.
Missing durations
If either side of a subtraction is NaT, the result is also missing. A missing Timedelta is shown as NaT as well. Methods like mean skip it by default, so check df["duration"].isna().sum() before trusting an average.
Exercise
A DataFrame has datetime columns opened and closed. Write one expression that returns the rows where a ticket stayed open for more than 36 hours, and explain why .dt.seconds > 36 * 3600 would give wrong results.
Show answer
Use df[(df["closed"] - df["opened"]) > pd.Timedelta(hours=36)]. The .dt.seconds attribute holds only the seconds left over after whole days are removed, so it never exceeds 86399. A ticket open for 3 days would show a small seconds value and be missed. Comparing against a Timedelta, or using total_seconds(), uses the full duration.