简体   繁体   中英

How to find the difference between two times in Python?

I am trying to find the difference between two times in Python. It is guaranteed that the times are on the same day.

#For example
s1 = '13:00' 
s2 = '12:58'

The difference between these two times should be 2 mins. The output should be: 2

This is my code:

from datetime import datetime
s1 = '13:00'
s2 = '12:58'
FMT = '%H:%M'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print(tdelta)

But it returns:

-1 day, 23:58:00

How can i fix this and return my time as: 2

You can try using abs for the result ie abs(datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)) :

from datetime import datetime
s1 = '13:00'
s2 = '12:58'
FMT = '%H:%M'
tdelta = abs(datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT))
print(tdelta)

Result:

0:02:00

Update:

As suggested in comment below, if you specifically want difference in minutes , you can use .total_seconds()/60 in tdelta :

from datetime import datetime
s1 = '13:00'
s2 = '12:58'
FMT = '%H:%M'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
minutes_difference = abs(tdelta.total_seconds()/60)
print(minutes_difference)

Result:

2.0

Here I like how this guy does it

also a little code snippet

from datetime import datetime

from dateutil.relativedelta import relativedelta

    t_a = datetime.now()
    t_b = datetime.now()

    def diff(t_a, t_b):
        t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
        return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

You could use the Python pandas library:

import pandas as pd

time_1 = pd.Timestamp('13:00')
time_2 = pd.Timestamp('12:58')
delta = time_1 - time_2
print(delta)

The Timestamp() method will allow you to create a simple Timestamp. Here is your output:

0 days 00:02:00

It takes as a given that the Timestamps are on the same day unless you specify otherwise.

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