I want to compare two dates and get the difference in seconds, such as get the seconds between a deadline and current datetime, but I'm getting some unexpected result when the subtrahend is greater than minuend
import datetime
deadline=datetime.datetime.strptime('2020-06-26 11:18:00','%Y-%m-%d %H:%M:%S')
current=datetime.datetime.strptime('2020-06-26 14:38:00','%Y-%m-%d %H:%M:%S')
result = (deadline - current).seconds #result is 74400
If you take a look, the day is the same for both datetimes, only the time part changes.
If I change the order of the "subtraction" I got a different result:
result = (current - deadline).seconds #result is 12000
I expected something like a negative result because current
is greater than deadline
, or at least the same seconds' value don't matter the order of the operands.
I would like to understand what is happening? And Is there a way to get always the same result?
version: python 3.7
You'll want to use .total_seconds()
if you want to know the elapsed time as opposed to the value of the "seconds" place in the timedelta.
In particular, the subtraction yielding 74400 is representing a -12000 second timedelta as -1 day and +74400 seconds internally. For the other subtraction it's representing it as +0 days and +12000 seconds, hence your results of 74400 and 12000 for .seconds
, respectively.