t1 = '11:19:04'
t2 = '11:19:07'
Being in this format : H:M:S
How can i get the time difference between the 2 strings?
you need to import datetime module which contains method to convert string time to datetime object, once you have converted your time to datetime object , you can simply substract themtry using this,
import datetime
t1 = '11:19:04'
t2 = '11:19:07'
t1_time=datetime.datetime.strptime(t1,"%H:%M:%S")
t2_time=datetime.datetime.strptime(t2,"%H:%M:%S")
print t2_time-t1_time
0:00:03
An alternative without the datetime module:
t1 = '11:19:04'
t2 = '11:19:07'
def t2s(t):
return sum(a*b for a, b in zip((int(x) for x in t.split(':')), (3600, 60, 1)))
print(t2s(t1) - t2s(t2))
It returns the difference as number of seconds.
Demo :
import datetime
t1 = '11:19:04' 'From'
t2 = '11:19:07' 'Till'
t1_time = datetime.datetime.strptime(t1, "%H:%M:%S")
t2_time = datetime.datetime.strptime(t2, "%H:%M:%S")
print t2_time - t1_time