Home > Mobile >  Unexpected datetime differencing with Python 3
Unexpected datetime differencing with Python 3

Time:11-17

I am using Python 3 - Linux Rocky 8. I am not getting the expected results when subtracting datetime objects.

import datetime
x = datetime.datetime.strptime('11 Nov 2022 17:36', '%d %b %Y %H:%M')
y = datetime.datetime.strptime('10 Nov 2022 17:30', '%d %b %Y %H:%M')
z = (x - y).seconds
print(str(z))
360

y = datetime.datetime.strptime('10 Nov 2022 17:40', '%d %b %Y %H:%M')
z = (x - y).seconds
print(str(z))
86160

I thought the time differences would 1 day 6 minutes and 1 day - 4 minutes.

CodePudding user response:

You're printing the .seconds attribute of a timedelta object. Not the total seconds

Look at x - y directly. In the first case.

datetime.timedelta(days=1, seconds=360)

In the second

datetime.timedelta(seconds=86160)

The seconds attribute will never be negative, and you do not have a full day.

Perhaps you wanted print(z.total_seconds())

  • Related