views:

161

answers:

1

I would like to add up a series of splits in Python. The times begin as strings like "00:08:30.291". I can't seem to find the right way to use the Python objects or API to make this convenient/elegant. It seems that the time object doesn't use microseconds, so I'm using datetime's strptime to parse the strings, successfully. But then datetimes don't seem to add, and I really prefer not to overflow into days (i.e. 23 + 2 hours = 25 hours). I can use datetime.time but they don't add either. Timedeltas would seem appropriate but seem a little awkward to convert from/to other things. Perhaps I am missing something obvious here. I would like to be able to:

for timestring in times:
    t = datetime.strptime("%H:%M:%S.%f", timestring).time
    total_duration = total_duration + t
print total_duration.strftime("%H:%M:%S.%f")
+5  A: 

What you're working with is time differences, that's why using datetime.timedelta is only appropriate here:

>>> import datetime
>>> d1 = datetime.datetime.strptime("00:08:30.291", "%H:%M:%S.%f")
>>> d1
datetime.datetime(1900, 1, 1, 0, 8, 30, 291000)
>>> d2
datetime.datetime(1900, 1, 1, 0, 2, 30, 291000)
>>> dt1 = datetime.timedelta(minutes=d1.minute, seconds=d1.second, microseconds=d1.microsecond)
>>> dt2 = datetime.timedelta(minutes=d2.minute, seconds=d2.second, microseconds=d2.microsecond)
>>> fin = dt1 + dt2
>>> fin
datetime.timedelta(0, 660, 582000)
>>> str(fin)
'0:11:00.582000'

Also, please don't use such names as sum for your variables, you're shadowing built-in.

SilentGhost
Certainly works but inelegant pulling apart the structure and recreating, especially for prototyping. Is there a neater/quicker way using the current API? Feels like timedelta should have strptime or something.
Sam Brightman
I renamed the variable in the question.
Sam Brightman
Likewise it is excluded from strftime, and it is doesn't seem simple to convert between even datetime and date/time: d1.time is still a datetime.
Sam Brightman