0

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

2 Answers2

4

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.

Hans Musgrave
  • 6,613
  • 1
  • 18
  • 37
2

If you are assuming that this is a bug in Python, it is not. What you have presented is a bug. Because this is how negative timedelta are represented in Python.

print (datetime.timedelta(seconds=-1).seconds)
# 86399

Because seconds in a timedelta are normalized to an amount between 0 and 86399.

Use .total_seconds() if you want a negative value.

result = (deadline - current).total_seconds()
print(result)
# -12000
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43