Difference between two dates in Python
Solution 1:
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)
Solution 2:
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()