# How to calculate the time interval between two time strings

### Question

I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly and keep finding only how to do this when a date is involved.

Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I'm storing them in a list. I now need to calculate the average. I'm using regular expressions to parse out the original times and then doing the differences.

For the averaging, should I convert to seconds and then average?

1
140
6/10/2017 2:05:41 PM

Yes, definitely `datetime` is what you need here. Specifically, the `strptime` function, which parses a string into a time 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.

177
2/19/2015 11:32:22 PM

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.