Python中两个日期之间的差异

时间:2022-12-08 02:59:38

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.

我有两个不同的日期,我想知道它们之间的天数差异。日期格式为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

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

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

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

我需要一个函数,我可以给两个日期,结果将是一个日期差异为天的int。

4 个解决方案

#1


151  

Use - to get the difference between two datetime objects and take the days member.

使用 - 获取两个日期时间对象之间的差异并获取days成员。

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)

#2


15  

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()

#3


2  

I tried the code posted by larsmans above but, there are a couple of problems:

我尝试过以上larsmans发布的代码,但是有一些问题:

1) The code as is will throw the error as mentioned by mauguerra 2) If you change the code to the following:

1)代码将抛出mauguerra提到的错误2)如果您将代码更改为以下代码:

...
    d1 = d1.strftime("%Y-%m-%d")
    d2 = d2.strftime("%Y-%m-%d")
    return abs((d2 - d1).days)

This will convert your datetime objects to strings but, two things

这会将你的日期时间对象转换为字符串,但有两件事

1) Trying to do d2 - d1 will fail as you cannot use the minus operator on strings and 2) If you read the first line of the above answer it stated, you want to use the - operator on two datetime objects but, you just converted them to strings

1)尝试做d2 - d1将失败,因为你不能在字符串上使用减号运算符和2)如果你读到上述答案的第一行它说,你想在两个日期时间对象上使用 - 运算符但是,你只是将它们转换为字符串

What I found is that you literally only need the following:

我发现你实际上只需要以下内容:

import datetime

end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)

print difference_in_days

#4


0  

Try this:

尝试这个:

data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)


m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()




m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()

#1


151  

Use - to get the difference between two datetime objects and take the days member.

使用 - 获取两个日期时间对象之间的差异并获取days成员。

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)

#2


15  

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()

#3


2  

I tried the code posted by larsmans above but, there are a couple of problems:

我尝试过以上larsmans发布的代码,但是有一些问题:

1) The code as is will throw the error as mentioned by mauguerra 2) If you change the code to the following:

1)代码将抛出mauguerra提到的错误2)如果您将代码更改为以下代码:

...
    d1 = d1.strftime("%Y-%m-%d")
    d2 = d2.strftime("%Y-%m-%d")
    return abs((d2 - d1).days)

This will convert your datetime objects to strings but, two things

这会将你的日期时间对象转换为字符串,但有两件事

1) Trying to do d2 - d1 will fail as you cannot use the minus operator on strings and 2) If you read the first line of the above answer it stated, you want to use the - operator on two datetime objects but, you just converted them to strings

1)尝试做d2 - d1将失败,因为你不能在字符串上使用减号运算符和2)如果你读到上述答案的第一行它说,你想在两个日期时间对象上使用 - 运算符但是,你只是将它们转换为字符串

What I found is that you literally only need the following:

我发现你实际上只需要以下内容:

import datetime

end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)

print difference_in_days

#4


0  

Try this:

尝试这个:

data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)


m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()




m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()