Importing datetime library
from datetime import timedelta
Add n days to Today's date
from datetime import date,datetime,timedelta
dt=date.today()
print("Today:",dt)
dt2=dt + timedelta(days=5) # 5 days
print("New Date: ",dt2)
Output
Today: 2019-09-19
New Date: 2019-09-24
Adding day and hours
from datetime import timedelta,date,datetime
dt=datetime.now()
dt2=dt + timedelta(days=5,hours=3)
print(dt2)
Output
2019-09-24 20:22:25.828862
Adding all options to present date and time
from datetime import timedelta,date,datetime
dt=datetime.now()
dt2=dt + timedelta(days=5,weeks=2,hours=3,minutes=5,seconds=4,microseconds=0.000001,milliseconds=123)
print(dt2)
Output
2019-10-07 11:22:38.468063
Difference in two datetime object
from datetime import timedelta,date,datetime
dt=datetime.now()
dt2=dt + timedelta(days=5)
dt3=dt + timedelta(days=4)
print(dt2-dt3)
Output
1 day, 0:00:00
Subtracting a month from today
from datetime import timedelta,date,datetime
month_delta=timedelta(days=-30)
dt=date.today()
print(dt+month_delta)
Output
2019-08-20
Adding 365 days
year_delta=timedelta(days=365)
dt=date.today()
print(dt+year_delta)
2020-09-18
This also takes care of leap years
import datetime
from datetime import timedelta
dt1=datetime.datetime(2018,3,1)
dt2=datetime.datetime(2019,3,1)
year_delta=timedelta(days=365)
print(dt1+year_delta)
print(dt2+year_delta)
Output
2019-03-01 00:00:00
2020-02-29 00:00:00
total_seconds()
We can get the seconds value of given timedelta
from datetime import timedelta,date,datetime
month_delta=timedelta(days=30)
print(month_delta.total_seconds())
Output
2592000.0
resolution
This is the minimum difference between timedelta objects
Using the above code
print(month_delta.resolution)
Output
0:00:00.000001
« All Date Objects
Date - Timetuple »
relativedelta »
← Subscribe to our YouTube Channel here