0
0
PandasHow-ToBeginner · 3 min read

How to Use Timedelta in Pandas for Date and Time Calculations

In pandas, use pd.Timedelta to represent a duration or difference between two dates or times. You can add or subtract Timedelta objects to datetime columns or series to shift dates by days, hours, minutes, etc.
📐

Syntax

The basic syntax to create a timedelta in pandas is using pd.Timedelta(value, unit), where value is a number and unit is a string like 'days', 'hours', 'minutes', 'seconds', etc.

You can also create timedeltas from strings like '2 days 3 hours'.

python
import pandas as pd

td1 = pd.Timedelta(5, unit='days')
td2 = pd.Timedelta('2 days 3 hours')
💻

Example

This example shows how to add a timedelta to a pandas datetime column to shift dates by a certain duration.

python
import pandas as pd

# Create a sample DataFrame with dates
df = pd.DataFrame({'date': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03'])})

# Create a timedelta of 3 days
three_days = pd.Timedelta(3, unit='days')

# Add timedelta to the date column
df['date_plus_3days'] = df['date'] + three_days

print(df)
Output
date date_plus_3days 0 2024-01-01 2024-01-04 1 2024-01-02 2024-01-05 2 2024-01-03 2024-01-06
⚠️

Common Pitfalls

One common mistake is trying to add or subtract timedeltas as strings directly without converting them to pd.Timedelta. This causes errors or unexpected results.

Also, mixing timedelta with non-datetime columns will not work.

python
import pandas as pd

# Wrong way: adding string directly
try:
    pd.Timestamp('2024-01-01') + '3 days'
except TypeError as e:
    print(f"Error: {e}")

# Right way: use pd.Timedelta
result = pd.Timestamp('2024-01-01') + pd.Timedelta('3 days')
print(result)
Output
Error: unsupported operand type(s) for +: 'Timestamp' and 'str' 2024-01-04 00:00:00
📊

Quick Reference

UsageDescriptionExample
pd.Timedelta(value, unit)Create timedelta with number and unitpd.Timedelta(5, unit='days')
pd.Timedelta('string')Create timedelta from stringpd.Timedelta('2 days 3 hours')
Add timedelta to datetimeShift datetime by timedeltadf['date'] + pd.Timedelta('3 days')
Subtract timedeltaShift datetime backwarddf['date'] - pd.Timedelta('1 hour')

Key Takeaways

Use pd.Timedelta to represent durations for date/time calculations in pandas.
Timedelta can be created from numbers with units or descriptive strings.
Add or subtract Timedelta objects to pandas datetime columns to shift dates.
Avoid adding strings directly to datetime; always convert to pd.Timedelta first.
Timedelta works only with datetime-like data, not with plain numbers or strings.