Sub topic 5
Measuring durations with Timedelta
This chapter covers how pandas represents an amount of time, how you get one from subtracting timestamps, and how to turn it into numbers you can report or filter on. It assumes you can already build Timestamp values and datetime columns with pd.to_datetime, and that you can filter rows with boolean masks. The examples were written for pandas 2.x.
What a Timedelta is
A Timedelta is a fixed length of elapsed time, such as "6 hours" or "1 day 2 hours 30 minutes". It has no start point and no calendar attached. A column of these values has dtype timedelta64[ns].
Compare the three core types:
| Type | Means | Example |
|---|---|---|
| `Timestamp` | One instant | `2024-03-01 09:30` |
| `Timedelta` | A fixed length of time | `1 days 02:30:00` |
| `Period` | A calendar span | `2024-03` (the month of March) |
A Timedelta is stored as an exact count of nanoseconds. Because of that, it cannot represent "one month" or "one year", since those lengths vary. Section "Why months and years are missing" returns to this.
Creating Timedeltas
You can build a single Timedelta from a string, from keyword arguments, or from a number plus a unit. Use pd.to_timedelta when you have many values at once.
import pandas as pd
a = pd.Timedelta("1 days 02:30:00")
b = pd.Timedelta(hours=1, minutes=15)
c = pd.Timedelta(90, unit="min")
print(a)
print(b)
print(c)
print(a.total_seconds())
print(pd.to_timedelta([1, 2, 3], unit="h"))The first three prints show 1 days 02:30:00, 0 days 01:15:00, and 0 days 01:30:00. a.total_seconds() returns 95400.0. The last line returns a TimedeltaIndex holding one, two, and three hours.
pd.to_timedelta works like pd.to_datetime. It accepts strings, numbers with a unit, and an errors argument. With errors="coerce", text that cannot be parsed becomes NaT, the same missing-value marker used for datetimes.
raw = pd.Series(["90min", "1 days 02:00:00", "bad"])
print(pd.to_timedelta(raw, errors="coerce"))This prints 0 days 01:30:00, 1 days 02:00:00, and NaT.
A bare number needs a unit. Without one, pd.to_timedelta treats numbers as nanoseconds, which is rarely what you want. Common unit codes are "D", "h", "min", "s", and "ms".
Where Timedeltas come from
Most Timedeltas are not typed by hand. They come out of arithmetic on timestamps. The rules are short:
- Timestamp minus Timestamp gives a Timedelta.
- Timestamp plus or minus a Timedelta gives a Timestamp.
- Timedelta plus or minus a Timedelta gives a Timedelta.
- Timedelta times or divided by a plain number gives a Timedelta.
- Timedelta divided by a Timedelta gives a plain float.
Here are those rules on scalars:
start = pd.Timestamp("2024-03-01 09:30")
end = pd.Timestamp("2024-03-03 08:00")
delta = end - start
print(delta)
print(start + pd.Timedelta(days=7))
print(delta * 2)
print(delta / pd.Timedelta(hours=1))
print(delta // pd.Timedelta(days=1))The outputs are 1 days 22:30:00, 2024-03-08 09:30:00, 3 days 21:00:00, 46.5, and 1.
Dividing by a Timedelta of the unit you want is the cleanest way to convert a duration to a number. delta / pd.Timedelta(hours=1) reads as "how many hours fit in delta", and the same pattern works for minutes or days. Floor division (//) answers "how many whole units fit".
Durations in a DataFrame
Subtracting two datetime columns gives a timedelta64[ns] column. This example measures how long orders take to ship. One order has not shipped yet, so its shipped value is missing.
orders = pd.DataFrame({
"created": pd.to_datetime(
["2024-03-01 09:30", "2024-03-01 11:00", "2024-03-02 16:45"]
),
"shipped": pd.to_datetime(
["2024-03-01 15:30", "2024-03-03 10:15", None]
),
})
orders["lead"] = orders["shipped"] - orders["created"]
print(orders["lead"])
print(orders["lead"].dtype)The lead column holds 0 days 06:00:00, 1 days 23:15:00, and NaT. The dtype is timedelta64[ns]. A missing timestamp on either side of the subtraction gives NaT, so missing data flows through the arithmetic without raising an error.
The other common source is diff(), which subtracts each row from the one before it. On a datetime column it gives the gaps between consecutive events.
df = pd.DataFrame({
"when": pd.to_datetime(
["2024-03-01 09:30", "2024-03-02 14:45", "2024-03-05 08:00"]
)
})
df["gap"] = df["when"].diff()
df["gap_hours"] = df["gap"].dt.total_seconds() / 3600
print(df)The first gap is NaT because the first row has no predecessor. The next two gaps are 1 days 05:15:00 and 2 days 17:15:00, which are 29.25 and 65.25 hours. The diff() method is covered in more detail in the chapter on shifting and rolling windows.
Reading a duration as a number
A timedelta64 column has its own .dt accessor, like datetime columns do. It exposes the pieces of a duration, and this is where most mistakes happen.
lead = orders["lead"]
print(lead.dt.total_seconds() / 3600)
print(lead.dt.days)
print(lead.dt.seconds)
print(lead.dt.components)For the second order (1 days 23:15:00), these give:
total_seconds() / 3600is47.25. This is the whole duration expressed in hours.daysis1. This is only the day part.secondsis83700. This is only the seconds left over after removing whole days (23 hours 15 minutes).componentsis a DataFrame with columnsdays,hours,minutes,seconds,milliseconds,microseconds, andnanoseconds.
The missing row gives NaN in each of these outputs, which also turns the integer results into floats.
Filtering, comparing, and summarizing
Timedeltas compare with other Timedeltas, so a boolean mask works as it does for numbers.
slow = orders[orders["lead"] > pd.Timedelta(hours=24)]
print(slow)Only the second order is returned. Comparisons with NaT evaluate to False, so the unshipped order is excluded here. If you want to flag unshipped orders instead, test orders["lead"].isna() explicitly.
Summaries work as you would expect, and they skip NaT by default:
print(orders["lead"].mean())
print(orders["lead"].sum())
print(orders["lead"].max())
print(orders["lead"].describe())The mean of 6 hours and 47.25 hours is 1 days 02:37:30, and the sum is 2 days 05:15:00. The result of mean() and sum() on a Timedelta column is itself a Timedelta, not a float.
To get tidier values, use round, floor, or ceil with a frequency string:
mean_lead = orders["lead"].mean()
print(mean_lead.round("h"))
print(mean_lead.floor("h"))
print(orders["lead"].dt.ceil("D"))These print 1 days 03:00:00, 1 days 02:00:00, and a column rounded up to whole days (1 days, 2 days, NaT). Use the lowercase "h" for hours. The uppercase "H" alias is deprecated in recent pandas versions.
Why months and years are missing
A Timedelta is an exact number of nanoseconds, so it only supports units with a fixed length: days, hours, minutes, seconds, and smaller. A month can be 28 to 31 days, and a year can be 365 or 366. In pandas 2.x, pd.Timedelta(1, unit="M") raises a ValueError for that reason.
When you mean a calendar step, use pd.DateOffset:
t = pd.Timestamp("2024-01-31")
print(t + pd.DateOffset(months=1))
print(t + pd.Timedelta(days=30))The first line prints 2024-02-29. The offset moves to the same position in the next month and clamps to the last valid day. The second line prints 2024-03-01, because 30 fixed days past January 31 lands in March.
Fixed durations and daylight saving time
The same distinction matters for time-zone-aware timestamps. A Timedelta of one day is always exactly 24 hours of elapsed time. A DateOffset of one day means "the same clock time on the next calendar day". On a day when clocks change, these differ.
t = pd.Timestamp("2024-03-09 12:00", tz="America/New_York")
print(t + pd.Timedelta(days=1))
print(t + pd.DateOffset(days=1))In New York, daylight saving time began at 2:00 a.m. on March 10, 2024. The first line prints 2024-03-10 13:00:00-04:00, because 24 elapsed hours land an hour later on the clock. The second prints 2024-03-10 12:00:00-04:00, because the clock time is preserved.
Choose by intent. Use Timedelta for elapsed time, such as timeouts, latencies, and service-level limits. Use DateOffset for calendar rules, such as "same time tomorrow" or "first of next month".
Common errors
- Using
.dt.secondsor.dt.daysas the total. Both return one component only. Usetotal_seconds()or divide by aTimedelta. - Subtracting columns of different kinds. A tz-aware column minus a tz-naive column raises a
TypeError. Localize or convert first, as covered in the time zones chapter. - Subtracting strings. If a column still has dtype
object, subtraction fails or gives nonsense. Convert withpd.to_datetimefirst. - Forgetting the unit on numbers.
pd.to_timedelta(5)is five nanoseconds. Passunit="min"or whichever unit you mean. - Assuming integer results. Any
NaTin the column makes.dt.daysand similar results float, so1appears as1.0. - Expecting a month or year unit. These are rejected. Use
DateOffsetor aPeriod.
Exercises
Exercise
A DataFrame column elapsed has dtype timedelta64[ns] and one value is 2 days 03:00:00. You want a float column holding each duration in minutes. Which expression do you use, and what does it return for that value? Why is elapsed.dt.seconds / 60 wrong?
Show answer
Use elapsed.dt.total_seconds() / 60, or equivalently elapsed / pd.Timedelta(minutes=1). For 2 days 03:00:00 the result is 3060.0 (51 hours times 60). elapsed.dt.seconds returns only the leftover seconds after whole days are removed, which is 10800 here, so dividing by 60 gives 180.0 and drops the two days.
Exercise
Given t = pd.Timestamp("2024-03-09 12:00", tz="America/New_York"), you need a reminder exactly 24 hours of elapsed time after t, and a second reminder at the same wall-clock time the next day. Write the two expressions and say which one lands at 13:00 local time.
Show answer
The first is t + pd.Timedelta(hours=24) (or days=1), which gives 2024-03-10 13:00:00-04:00 because clocks moved forward an hour overnight. The second is t + pd.DateOffset(days=1), which gives 2024-03-10 12:00:00-04:00. The Timedelta version lands at 13:00 local time.