mauguerra mauguerra - 1 year ago 81
Python Question

Difference between two dates?

Im programming with PYTHON...

I have two diferent dates...and I want to know the difference (in days) between them. The format of the date is YYYY-MM-DD

To explain myself in a better way...

I have a function that can ADD or SUBSTRACT a given number and get the date....for example:

def addonDays(a,x):
ret = time.strftime("%Y-%m-%d",time.localtime(time.mktime(time.strptime(a,"%Y-%m-%d"))+x*3600*24+3600))
return ret

where A is the date and X the number of days I want to add.....and the result is another date....

I need a function where I can give two dates and the result would be an int with the days of difference....

I hope someone could help!!

Answer Source

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)