How to calculate number of days between two given dates
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping
--
Chapters
00:00 Question
00:18 Accepted answer (Score 1137)
00:43 Answer 2 (Score 216)
00:59 Answer 3 (Score 61)
01:17 Answer 4 (Score 24)
01:45 Thank you
--
Full question
https://stackoverflow.com/questions/1511...
Accepted answer links:
[timedelta]: https://docs.python.org/3/library/dateti...
https://docs.python.org/library/datetime...
[this answer]: https://stackoverflow.com/a/8258465
Answer 3 links:
[here]: https://web.archive.org/web/200610070155...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #date #datetime
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping
--
Chapters
00:00 Question
00:18 Accepted answer (Score 1137)
00:43 Answer 2 (Score 216)
00:59 Answer 3 (Score 61)
01:17 Answer 4 (Score 24)
01:45 Thank you
--
Full question
https://stackoverflow.com/questions/1511...
Accepted answer links:
[timedelta]: https://docs.python.org/3/library/dateti...
https://docs.python.org/library/datetime...
[this answer]: https://stackoverflow.com/a/8258465
Answer 3 links:
[here]: https://web.archive.org/web/200610070155...
--
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