How to calculate number of days between two given dates? How to calculate number of days between two given dates? python python

How to calculate number of days between two given dates?


If you have two date objects, you can just subtract them, which computes a timedelta object.

from datetime import dated0 = date(2008, 8, 18)d1 = date(2008, 9, 26)delta = d1 - d0print(delta.days)

The relevant section of the docs:https://docs.python.org/library/datetime.html.

See this answer for another example.


Using the power of datetime:

from datetime import datetimedate_format = "%m/%d/%Y"a = datetime.strptime('8/18/2008', date_format)b = datetime.strptime('9/26/2008', date_format)delta = b - aprint delta.days # that's it


Days until Christmas:

>>> import datetime>>> today = datetime.date.today()>>> someday = datetime.date(2008, 12, 25)>>> diff = someday - today>>> diff.days86

More arithmetic here.