tags:

views:

73

answers:

5

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. I'm using Python 2.6.5 on Windows XP.

Thanks.

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?

+2  A: 

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(s1, FMT) - datetime.strptime(s2, 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.

David Zaslavsky
+1  A: 

Structure that represent time difference in Python is called timedelta. If you have start_time and end_time which represents time or 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.

Lukasz Dziedzia
A: 

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

ChrisF
A: 

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.

Pierce
A: 

This site say to do:

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

Kyra