marlon
marlon

Reputation: 7653

Why is the diff of two datetime objects so?

datetime1 = '2020-08-19 10:13:19'
datetime2 = '2020-08-19 19:00:00'

diff = datetime1 - datetime2

The diff is a timedelta object, with:

diff.days = -1
diff.seconds = 54766 = 15.22 hours

There are only about 9 hours diff between the two datetimes. Why does it show the number of days is '1' and 15.22 hours? How to understand the diff of two datetimes?

Upvotes: 1

Views: 102

Answers (2)

jsmart
jsmart

Reputation: 3001

In this example, the difference between two datetime objects has a negative number of days, and a positive number of hours.

import datetime
datetime1 = datetime.datetime.fromisoformat('2020-08-19 10:13:19')
datetime2 = datetime.datetime.fromisoformat('2020-08-19 19:00:00')

print(datetime1 - datetime2)
-1 day, 15:13:19

# divide by timedelta() (with argument of hours, minutes, seconds, etc.
print((datetime1 - datetime2) / datetime.timedelta(hours=1)) # in hours
-8.778055555555556

Here is an interesting interview with the core developer who maintains date / time in CPython: https://talkpython.fm/episodes/show/271/unlock-the-mysteries-of-time-pythons-datetime-that-is

UPDATE

You can calculate time difference in minutes, or days, or other units, by supplying a different parameter to .timedelta():

print((datetime1 - datetime2) / datetime.timedelta(minutes=1)) # in minutes
-526.68

print((datetime1 - datetime2) / datetime.timedelta(days=1)) # in days
-0.3658

Upvotes: 0

Wups
Wups

Reputation: 2569

If you subtract the earlier datetime from the later datetime, you get a positive timedelta, as one would expect.

The other way around, you get a negative timedelata in the unusual format.
But when you calculate -1 day + 15 hours = -24 hours + 15 hours = -9 hours, the result is correct.
Of course, doing this calculation manually is not what we want.

So, either avoid subtracting a later datetime from an earlier datetime:

# to get an absolute timedelta
if datetime2 > datetime1:
    print(datetime2 - datetime1)
else:
    print(datetime1 - datetime2)

Or use .total_seconds():

print((datetime1 - datetime2).total_seconds())
-31601.0
print((datetime2 - datetime1).total_seconds())
31601.0

Upvotes: 2

Related Questions