Python timedelta is a class of datetime.timedelta which usually used to perform datetime object manipulations, such as adding or substracting a certain amount of time between two dates or times. And timedelta object can be created by passing in the number of days, seconds, microseconds, milliseconds, minutes, hours, or weeks as arguments. Please see below syntax:
Syntax:
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Return: Date
Below the steps to use timedelta class:
- Load the packages: import
pandasandtimedeltamodule form Python’s build-indatetimepackages - Convert the date string to
datetimeusing pandasto_datetimefunction - Add and/or Substracting from dates
- Convert the result to date string (if needed)
For Example:
import pandas as pd
from datetime import timedelta
date = '2023-01-17' # date string
date = pd.to_datetime(date)
date_subs_7 = date - timedelta(days=7)
date_subs_7 = date_subs_7.strftime("%Y-%m-%d")
date_add_7 = date + timedelta(days=7)
date_add_7 = date_add_7.strftime("%Y-%m-%d")
print(date_subs_7, '\r\n', date_add_7)
Output:
2023-01-10
2023-01-24
The code above will return the date 7 days prior and 7 days following the date = '2023-01-17'.