How to calculate the time interval between two time strings
Solution 1:
Yes, definitely datetime
is what you need here. Specifically, the datetime.strptime()
method, which parses a string into a datetime
object.
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
That gets you a timedelta
object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime
.
This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00
and s2 = 05:00:00
. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:
if tdelta.days < 0:
tdelta = timedelta(
days=0,
seconds=tdelta.seconds,
microseconds=tdelta.microseconds
)
(of course you need to include from datetime import timedelta
somewhere). Thanks to J.F. Sebastian for pointing out this use case.
Solution 2:
Try this -- it's efficient for timing short-term events. If something takes more than an hour, then the final display probably will want some friendly formatting.
import time
start = time.time()
time.sleep(10) # or do something more productive
done = time.time()
elapsed = done - start
print(elapsed)
The time difference is returned as the number of elapsed seconds.