1

When subtracting dates in python I'm finding that the results are not symmetric and the magnitude of difference depends on the order of subtraction

Code

import sys
from datetime import datetime, timezone, timedelta
print(sys.version)

datetime_1 = datetime.fromisoformat('2020-01-19 21:00:00').astimezone(timezone.utc)
datetime_2 = datetime_1 + timedelta(hours=1)
print(datetime_1)
print(datetime_2)

print(datetime_1 - datetime_2)
print(datetime_2 - datetime_1)

print((datetime_2 - datetime_1).seconds)
print((datetime_1 - datetime_2).seconds)

Output

> 3.7.2 (default, Dec 29 2018, 06:19:36)  [GCC 7.3.0]
> 2020-01-20 05:00:00+00:00 
> 2020-01-20 06:00:00+00:00
> -1 day, 23:00:00
> 1:00:00
> 3600
> 82800

My expectation is that the difference would be 3600 seconds, ignoring the sign, regardless of the order of subtraction. Any idea why this is not the case?

canyon289
  • 3,355
  • 4
  • 33
  • 41

1 Answers1

1

Ended up getting an answer from someone else I knew. The trick is to use total_seconds()

print((datetime_2 - datetime_1).total_seconds())
print((datetime_1 - datetime_2).total_seconds())

Same person gave me a link to the same question that I missed (making this question a duplicate)

How do I check the difference, in seconds, between two dates?

canyon289
  • 3,355
  • 4
  • 33
  • 41