-1
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?

Carla
  • 11
  • 1

3 Answers3

2

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
pushpendra chauhan
  • 2,205
  • 3
  • 20
  • 29
0

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.

VPfB
  • 14,927
  • 6
  • 41
  • 75
0
  • Import datetime module:
  • Pass the striptime value to the String
  • Subtract the 't2' to 't1'
  • 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
    
Lucifer Rodstark
  • 206
  • 4
  • 14