How to subtract Python timedelta from date in Python?


You can subtract a day from a Python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date. 

Example

from datetime import datetime
from datetime import timedelta
today = datetime.today()
yesterday = today - timedelta(days=1)
print(today)
print()
print(yesterday)

Output

This will give the output −

2017-12-29 12:28:06.531791
2017-12-28 12:28:06.531791

You can also subtract years, months, hours, etc. in the same way from a date using the timedelta object.

Updated on: 02-Nov-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements