Problem statement
It seems like there is a bug in python datetime module, following code snippet should be self-explanatory:
import datetime
dep = datetime.datetime(2021, 9, 11, 7, 25)
arr = datetime.datetime(2021, 9, 11, 12, 35)
print(f"expected: -5h10m, real: {dep - arr}")
print(f"expected: 5h10m, real: {arr - dep}")
What I get with python 3.10:
expected: -5h10m, real: -1 day, 18:50:00
expected: 5h10m, real: 5:10:00
Question
Is it a bug or a feature? If it is a bug, what can I do to fix it?
It is a feature - subtraction of datetime from datetime results in a timedelta object, which is normalised so that only negative value can be days.
That behaviour is documented, eg. here: https://pl.python.org/docs/lib/datetime-timedelta.html
I would call this effect
expected: -5h10m, real: -1 day, 18:50:00
expected: 5h10m, real: 5:10:00
glitch, as it is limited solely to look, whilst both deltas hold same amount of seconds and are equal to their opposite, which can be checked as follows
import datetime
dep = datetime.datetime(2021, 9, 11, 7, 25)
arr = datetime.datetime(2021, 9, 11, 12, 35)
delta1 = dep - arr
delta2 = arr - dep
print(delta1.total_seconds()) # -18600.0
print(delta2.total_seconds()) # 18600.0
print(delta1 == -delta2) # True
print(delta2 == -delta1) # True
print(delta1 + delta2) # 0:00:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With