Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 993
Ray Avatar asked Sep 29 '08 23:09

Ray


People also ask

How do I calculate the number of days between two dates in Excel?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered. Note that Excel recognizes leap years.

How do I calculate the number of days between two dates in Python?

Using Python datetime module: Python comes with an inbuilt datetime module that helps us to solve various datetime related problems. In order to find the difference between two dates we simply input the two dates with date type and subtract them, which in turn provides us the number of days between the two dates.


3 Answers

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.

like image 57
Dana Avatar answered Oct 08 '22 18:10

Dana


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
like image 20
dguaraglia Avatar answered Oct 08 '22 18:10

dguaraglia


Days until Christmas:

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

More arithmetic here.

like image 56
Harley Holcombe Avatar answered Oct 08 '22 16:10

Harley Holcombe