Computer >> Computer tutorials >  >> Programming >> Python

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.