How to calculate number of days between two given dates?


If I have two dates (ex. '8/18/2008' and '9/26/2008'), what is the best way to get the number of days between these two dates?

12/23/2018 10:14:17 PM

Accepted Answer

If you have two date objects, you can just subtract them.

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:

2/16/2019 6:21:00 AM

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 # that's it

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow