โ Pandas Timedelta Support โ Handle Duration & Time Differences with Ease
๐งฒ Introduction โ What Is Timedelta in Pandas?
A Timedelta in Pandas represents a duration or time difference between two datetime values. Whether you’re calculating time lags, scheduling tasks, or tracking durations, Pandas provides Timedelta, TimedeltaIndex, and .dt accessors for fast and flexible operations.
๐ฏ In this guide, youโll learn:
- How to create and manipulate timedelta objects
- Perform arithmetic with datetimes and timedeltas
- Extract duration components (days, seconds, etc.)
- Work with timedeltas in DataFrames and Series
๐ฅ 1. Create Timedelta Objects
import pandas as pd
pd.Timedelta(days=5)
pd.Timedelta('2 days 6 hours 30 minutes')
โ๏ธ Supports both explicit parameters and string-based durations.
๐งฎ 2. Calculate Time Differences Between Dates
df = pd.DataFrame({
'Start': pd.to_datetime(['2023-01-01', '2023-01-05']),
'End': pd.to_datetime(['2023-01-03', '2023-01-10'])
})
df['Duration'] = df['End'] - df['Start']
๐ Output:
Start End Duration
0 2023-01-01 2023-01-03 2 days
1 2023-01-05 2023-01-10 5 days
โ๏ธ Subtracting datetime columns automatically creates a timedelta.
๐ข 3. Extract Components of Timedelta
df['Duration'].dt.days # Get number of full days
df['Duration'].dt.total_seconds() / 3600 # Convert to hours
โ๏ธ Use .dt accessor to pull numeric components.
๐ 4. Perform Arithmetic with Timedeltas
df['End'] + pd.Timedelta(days=3) # Add 3 days to each datetime
df['Start'] - pd.Timedelta(hours=12) # Subtract 12 hours
โ๏ธ Add or subtract timedelta to/from datetime columns.
๐งฑ 5. Create Series of Timedeltas
pd.to_timedelta(['1D', '2D 03:00:00', '4.5H', '00:45:00'])
๐ Output:
0 1 days 00:00:00
1 2 days 03:00:00
2 0 days 04:30:00
3 0 days 00:45:00
dtype: timedelta64[ns]
โ๏ธ Vectorized creation from duration-like strings.
๐ 6. Generate Timedelta Ranges
pd.timedelta_range(start='0s', periods=5, freq='2H')
๐ Output:
TimedeltaIndex(['00:00:00', '02:00:00', '04:00:00', '06:00:00', '08:00:00'],
dtype='timedelta64[ns]', freq='2H')
โ๏ธ Similar to date_range, but for durations.
๐งผ 7. Convert Numeric Columns to Timedelta
df = pd.DataFrame({'Minutes': [30, 90, 120]})
df['Duration'] = pd.to_timedelta(df['Minutes'], unit='m')
โ๏ธ Quickly convert raw numeric time data (seconds, minutes, etc.) into Timedelta.
๐ Summary โ Key Takeaways
Pandas makes it easy to compute and manage durations using its robust Timedelta tools. Whether working with timestamps or numeric time differences, the functionality is clean, fast, and highly expressive.
๐ Key Takeaways:
- Use
pd.Timedelta()andto_timedelta()to create durations - Subtract datetime values to get timedelta
- Use
.dtto extract days, seconds, hours, etc. - Combine with datetime operations for time shifts
- Use
timedelta_range()to create intervals
โ๏ธ Real-world relevance: Used in event log analysis, project tracking, time-based SLAs, and duration-based KPIs.
โ FAQs โ Timedelta in Pandas
โ How do I convert timedelta to hours or minutes?
Use:
df['Duration'].dt.total_seconds() / 3600 # for hours
โ Can I sort a column with timedelta?
โ
Yes. Timedelta values are sortable like numbers.
โ Whatโs the difference between .days and .total_seconds()?
.dt.daysโ full days only.dt.total_seconds()โ total duration including fractional parts
โ How can I round a timedelta?
Use:
df['Duration'].dt.round('min')
Share Now :
