Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 681
user956424 Avatar asked Sep 05 '25 01:09

user956424


2 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.

like image 170
davidism Avatar answered Sep 06 '25 17:09

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
like image 42
Al Martins Avatar answered Sep 06 '25 17:09

Al Martins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!