user956424
user956424

Reputation: 1609

Does timedelta added to date consider leap year?

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?

Upvotes: 4

Views: 4729

Answers (2)

Al Martins
Al Martins

Reputation: 436

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

Upvotes: 1

davidism
davidism

Reputation: 127320

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.

Upvotes: 11

Related Questions