How to calculate the time interval between two time strings How to calculate the time interval between two time strings python python

How to calculate the time interval between two time strings


Yes, definitely datetime is what you need here. Specifically, the datetime.strptime() method, which parses a string into a datetime object.

from datetime import datetimes1 = '10:33:26's2 = '11:15:49' # for exampleFMT = '%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 timestart = time.time()time.sleep(10)  # or do something more productivedone = time.time()elapsed = done - startprint(elapsed)

The time difference is returned as the number of elapsed seconds.


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 pythonfrom datetime import datetime, time as datetime_time, timedeltadef 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 - startfor 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:230: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 pythonfrom datetime import timedeltadef 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:00print(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.