timedelta – add days and substract days from dates

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:

  1. Load the packages: import pandas and timedelta module form Python’s build-in datetime packages
  2. Convert the date string to datetime using pandas to_datetime function
  3. Add and/or Substracting from dates
  4. 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'.

Leave a comment