Difference between two time intervals in Python

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?

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.

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)
``````

Structure that represent time difference in Python is called timedelta. If you have `start_time` and `end_time` as `datetime` types you can calculate the difference using `-` operator like:

``````diff = end_time - start_time
``````

you should do this before converting to particualr string format (eg. before start_time.strftime(...)). In case you have already string representation you need to convert it back to time/datetime by using strptime method.

This site says to try:

``````import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt)
diff.seconds/60
``````

This forum uses time.mktime()

Here's a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as `23:55:00-00:25:00` (a half an hour duration):

``````#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta

def time_diff(start, end):
if isinstance(start, datetime_time): # convert to datetime
assert isinstance(end, datetime_time)
start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
if start <= end: # e.g., 10:33:26-11:15:49
return end - start
else: # end < start e.g., 23:55:00-00:25:00
end += timedelta(1) # +day
assert end > start
return end - start

for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
print(time_diff(s, e))
assert time_diff(s, e) == time_diff(s.time(), e.time())
``````

Output

``````0:42:23
0:30:00
``````

`time_diff()` returns a timedelta object that you can pass (as a part of the sequence) to a `mean()` function directly e.g.:

``````#!/usr/bin/env python
from datetime import timedelta

def mean(data, start=timedelta(0)):
"""Find arithmetic average."""
return sum(data, start) / len(data)

data = [timedelta(minutes=42, seconds=23), # 0:42:23
timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds
``````

The `mean()` result is also `timedelta()` object that you can convert to seconds (`td.total_seconds()` method (since Python 2.7)), hours (`td / timedelta(hours=1)` (Python 3)), etc.

Both `time` and `datetime` have a date component.

Normally if you are just dealing with the time part you'd supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a `datetime` for each with the day set to today and subtract the start from the stop time to get the interval (`timedelta`).

Take a look at the datetime module and the timedelta objects. You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.

I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.

But looks neat for me :)

``````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_a, t_b)
return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)
``````

Regarding to the question you still need to use `datetime.strptime()` as others said earlier.