如何在减去相同的两个日期时将计算设为1天

时间:2015-07-31 06:40:39

标签: python date django-views

这是我计算两个给定日期之间差异的代码

days = datetime.strptime(todate, "%Y-%m-%d") - datetime.strptime(fromdate, "%Y-%m-%d")
print days

工作正常。然而,问题是当给出两个相同的日期,即todate = 2015-07-31, fromdate = 2015-07-31时,它将其计算为0天。我希望如果todatefromdate相同,则计算应为1而不是0.

2 个答案:

答案 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)