0
0
Pandasdata~5 mins

Date arithmetic with timedelta in Pandas

Choose your learning style9 modes available
Introduction

We use date arithmetic to add or subtract time from dates. This helps us find new dates easily.

To find a date 7 days after a given date, like a deadline.
To calculate the difference between two dates in days.
To shift dates in a dataset for analysis, like forecasting.
To filter data within a certain date range.
To add hours or minutes to timestamps for scheduling.
Syntax
Pandas
from pandas import Timestamp, Timedelta

new_date = Timestamp('YYYY-MM-DD') + Timedelta(days=number)

Timestamp represents a date or time.

Timedelta represents a duration to add or subtract.

Examples
Adds 10 days to January 1, 2024.
Pandas
from pandas import Timestamp, Timedelta

start = Timestamp('2024-01-01')
new_date = start + Timedelta(days=10)
print(new_date)
Subtracts 2 weeks from January 15, 2024.
Pandas
from pandas import Timestamp, Timedelta

start = Timestamp('2024-01-15')
new_date = start - Timedelta(weeks=2)
print(new_date)
Adds 5 hours and 30 minutes to a timestamp.
Pandas
from pandas import Timestamp, Timedelta

start = Timestamp('2024-01-01 08:00')
new_time = start + Timedelta(hours=5, minutes=30)
print(new_time)
Sample Program

This program shows how to add or subtract days, weeks, and hours from a date using pandas Timedelta.

Pandas
import pandas as pd

# Create a start date
start_date = pd.Timestamp('2024-06-01')

# Add 15 days
date_plus_15 = start_date + pd.Timedelta(days=15)

# Subtract 3 weeks
date_minus_3weeks = start_date - pd.Timedelta(weeks=3)

# Add 2 days and 4 hours
date_plus_days_hours = start_date + pd.Timedelta(days=2, hours=4)

print(f"Start date: {start_date}")
print(f"Date plus 15 days: {date_plus_15}")
print(f"Date minus 3 weeks: {date_minus_3weeks}")
print(f"Date plus 2 days and 4 hours: {date_plus_days_hours}")
OutputSuccess
Important Notes

You can combine days, weeks, hours, minutes, and seconds in Timedelta.

Timedelta works well with pandas Timestamp and datetime columns in DataFrames.

Subtracting Timedelta moves the date backward.

Summary

Date arithmetic helps change dates by adding or subtracting time.

Use pandas Timedelta to represent the time difference.

Combine Timedelta with Timestamp to get new dates easily.