这是我计算两个给定日期之间差异的代码
days = datetime.strptime(todate, "%Y-%m-%d") - datetime.strptime(fromdate, "%Y-%m-%d")
print days
工作正常。然而,问题是当给出两个相同的日期,即todate = 2015-07-31, fromdate = 2015-07-31
时,它将其计算为0天。我希望如果todate
和fromdate
相同,则计算应为1而不是0.
答案 0 :(得分:1)
使用布尔运算符:
from datetime import datetime, timedelta
days = datetime.strptime(todate, "%Y-%m-%d") - datetime.strptime(fromdate, "%Y-%m-%d")
days = days or timedelta(days=1)
答案 1 :(得分:1)
如何使用max
限制返回值不低于一天。
days = max(timedelta(days=1),
datetime.strptime(todate, "%Y-%m-%d") -
datetime.strptime(fromdate, "%Y-%m-%d"))
>>> fromdate = '2015-07-31'
>>> todate = '2015-07-31'
>>> days = max(timedelta(days=1),
... datetime.strptime(todate, "%Y-%m-%d") -
... datetime.strptime(fromdate, "%Y-%m-%d"))
>>> days
datetime.timedelta(1)