🔟 ⏱️ Pandas Time Series & Sparse Data
Estimated reading: 3 minutes 305 views

⌛ 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() and to_timedelta() to create durations
  • Subtract datetime values to get timedelta
  • Use .dt to 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 :
Share

Pandas Timedelta Support

Or Copy Link

CONTENTS
Scroll to Top