Python中两个日期之间的差异

问题描述:

我有两个不同的日期,我想知道它们之间的天数差异。日期的格式为YYYY-MM-DD。

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

我有一个可以将给定数字添加或减去到日期的函数:

I have a function that can ADD or SUBTRACT a given number to a date:

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

其中A是日期,x是我要添加的天数。结果是另一个日期。

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 date difference in days.

使用-来获取两个 datetime之间的时差对象并接受成员。

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)