-1

I came across a strange behavior of the datetime module of Python3: I calculate the difference between the dates "date" and "mon", and then add to the "date" first the resulting difference as it is, and then add to the "date" the resulting difference converted into seconds. But for some reason, the dates are different, although they should be the same. Please tell me what I'm doing wrong.

date=datetime.datetime(2021,9,4,13,00)
mon=datetime.datetime(2021, 9, 6, 0, 0)
delta=mon-date
print(date+delta)
print(date+datetime.timedelta(seconds=(delta).seconds))

result:

2021-09-06 00:00:00

2021-09-05 00:00:00

FObersteiner
  • 22,500
  • 8
  • 42
  • 72

1 Answers1

1

datetime.timedelta.seconds attribute does not represent the total number of seconds in the period. There is datetime.timedelta.total_seconds() method for for that.

import datetime
date=datetime.datetime(2021,9,4,13,00)
mon=datetime.datetime(2021, 9, 6, 0, 0)
delta=mon-date
print(delta, delta.seconds)
print(delta == datetime.timedelta(seconds=delta.seconds))
print(date+delta)
print(date+datetime.timedelta(seconds=delta.total_seconds()))

output

1 day, 11:00:00 39600
False
2021-09-06 00:00:00
2021-09-06 00:00:00

As stated in the docs the timedelta.seconds attribute is seconds between 0 and 86399 inclusive.

buran
  • 13,682
  • 10
  • 36
  • 61