Days between two dates? [duplicate]
What's the shortest way to see how many full days have passed between two dates? Here's what I'm doing now.
math.floor((b - a).total_seconds()/float(86400))
Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting timedelta
object for the number of days:
>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7
And it works with datetimes too — I think it rounds down to the nearest day:
>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6
Do you mean full calendar days, or groups of 24 hours?
For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:
days = (a - b).days
For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:
roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days