Does timedelta added to date consider leap year?

Question:

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 By: user956424

||

Answers:

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.

Answered By: davidism

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
Answered By: Al Martins
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.