The Python Oracle

How to calculate number of days between two given dates

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2

--

Chapters
00:00 How To Calculate Number Of Days Between Two Given Dates
00:13 Accepted Answer Score 1216
00:35 Answer 2 Score 240
00:49 Answer 3 Score 64
01:03 Answer 4 Score 24
01:22 Thank you

--

Full question
https://stackoverflow.com/questions/1511...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #date #datetime

#avk47



ACCEPTED ANSWER

Score 1216


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.




ANSWER 2

Score 240


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 how to calculate number of days between two given dates



ANSWER 3

Score 64


Days until Christmas:

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

More arithmetic here.




ANSWER 4

Score 24


You want the datetime module.

>>> from datetime import datetime 
>>> datetime(2008,08,18) - datetime(2008,09,26) 
datetime.timedelta(4) 

Another example:

>>> import datetime 
>>> today = datetime.date.today() 
>>> print(today)
2008-09-01 
>>> last_year = datetime.date(2007, 9, 1) 
>>> print(today - last_year)
366 days, 0:00:00 

As pointed out here