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

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 date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(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 datetime
date_format = %m/%d/%Y
a = datetime.strptime(8/18/2008, date_format)
b = datetime.strptime(9/26/2008, date_format)
delta = b - a
print delta.days # thats it

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

Days until Christmas:

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

More arithmetic here.

Leave a Reply

Your email address will not be published. Required fields are marked *