简体   繁体   中英

How do I calculate difference between 2 datetime in python

I want to calculate the difference between two timestamps in seconds, for example:

t1 = "12:59:54"
t2 = "01:00:14"

So the difference should be 20 seconds. (Note that dates are strings in my case.) And how would I know if t1 > t2 or vice-versa?

What I have tried so far:

t1 = datetime.strptime(t1, "%H:%M:%S")
t2 = datetime.strptime(t2, "%H:%M:%S")

if t1 > t2:
    difference = t1 - t2
else:
    difference = t2 - t1
print(difference.total_seconds())

This prints 43180, but it should be 20, right?

You have two times:

t1 = "12:59:54"
t2 = "01:00:14"

You say these are 20 seconds apart, but that is not correct. The first time is about an hour after mid-day, while the second is about an hour after midnight.

You probably want:

t2 = "13:00:14"

In other words, 24-hour time. Or you can do some math yourself if the difference between your times is more than 12 hours, perhaps you want to subtract 12 hours and assume that's what the input was supposed to mean.

Another alternative would be to add explicit "AM" and "PM" suffixes to the strings, which strptime() can parse if given %p in the format string.

you need to use t2 = "13:00:14"`instead of 01:00:14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM