โŒ› 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Pandas Timedelta Support

Or Copy Link

CONTENTS
Scroll to Top