Reputation: 59
Here is my code for calculating the difference between two given dates
days = datetime.strptime(todate, "%Y-%m-%d") - datetime.strptime(fromdate, "%Y-%m-%d")
print days
It works fine. However, the problem is when given two same dates i.e todate = 2015-07-31, fromdate = 2015-07-31
, it calculates it as 0 days. I want that if the todate
and fromdate
is same the calculation should be 1 not 0.
Upvotes: 1
Views: 53
Reputation: 369054
How about using max
to limit return value is not lower than a day.
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)
Upvotes: 1
Reputation: 19627
Using boolean operator maybe:
from datetime import datetime, timedelta
days = datetime.strptime(todate, "%Y-%m-%d") - datetime.strptime(fromdate, "%Y-%m-%d")
days = days or timedelta(days=1)
Upvotes: 1