Python中两个日期之间的差异 [英] Difference between two dates in Python
本文介绍了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)
这篇关于Python中两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文