Example Suppose for a given date, when we add timedelta(days=180), and get the new date, does it consider the leap year and calculate the new date? Or do we exclusively calculate the leap year of the current date whether Feb has 28 / 29 days and get the new date accordingly in python datetime.datetime object?
Asked
Active
Viewed 3,760 times
2
-
5Did you try it? What happened? – wwii Dec 15 '14 at 04:44
2 Answers
11
Try it out:
from datetime import datetime, timedelta
dt = datetime(2012, 2, 27)
print(dt + timedelta(3)) # March 1st
If it didn't handle February 29th, I would expect this to say March 2nd. So yes, Python's datetime knows about leap years.

davidism
- 121,510
- 29
- 395
- 339
0
And one must be very careful using +timedelta(days=365).
from datetime import datetime, timedelta
dt = datetime(2012, 2, 27)
print (dt+timedelta(days=365)) # 2013-02-26
dt = datetime(2013, 2, 27)
print(dt + timedelta(3)) # 2013-03-02

Al Martins
- 431
- 5
- 13