Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime wrong deduction

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?

like image 278
Petr Dvořáček Avatar asked Aug 30 '26 05:08

Petr Dvořáček


2 Answers

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

like image 189
matszwecja Avatar answered Aug 31 '26 18:08

matszwecja


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
like image 41
Daweo Avatar answered Aug 31 '26 19:08

Daweo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!