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))
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
timedelta
doesn’t report any unit longer than days (although I could be wrong).
Nov 25, 2011 at 11:28
timedelta
returned 0 in those cases, which is not what I wanted. I was looking for the date difference. As a solution, I converted the datetime to date and it worked as I expected!
Nov 10, 2020 at 23:02
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
Referencing my comments on other answers. This is how I would work out the difference in days based on 24 hours and calender days. the days attribute works well for 24 hours and the function works best for calendar checks.
from datetime import timedelta, datetime
def cal_days_diff(a,b):
A = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
B = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
return (A - B).days
if __name__ == '__main__':
x = datetime(2013, 06, 18, 16, 00)
y = datetime(2013, 06, 19, 2, 00)
print (y - x).days # 0
print cal_days_diff(y, x) # 1
z = datetime(2013, 06, 20, 2, 00)
print (z - x).days # 1
print cal_days_diff(z, x) # 2