Difference between two dates in Python
You can use the third-party library dateutil
, which is an extension for the built-in datetime
.
Parsing dates with the parser
module is very straightforward:
from dateutil import parser
date1 = parser.parse('2019-08-01')
date2 = parser.parse('2019-08-20')
diff = date2 - date1
print(diff)
print(diff.days)
Answer based on the one from this deleted duplicate
Use -
to get the difference between two datetime
objects and take the days
member.
from datetime import datetime
def days_between(d1, d2):
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
return abs((d2 - d1).days)
Another short solution:
from datetime import date
def diff_dates(date1, date2):
return abs(date2-date1).days
def main():
d1 = date(2013,1,1)
d2 = date(2013,9,13)
result1 = diff_dates(d2, d1)
print '{} days between {} and {}'.format(result1, d1, d2)
print ("Happy programmer's day!")
main()