views:

122

answers:

5
+2  Q: 

Python sum up time

In python how to sum up the following time

 0:00:00
 0:00:15
 9:30:56

Thanks..

+3  A: 

As a list of strings?

timeList = [ '0:00:00', '0:00:15', '9:30:56' ]
totalSecs = 0
for tm in timeList:
    timeParts = [int(s) for s in tm.split(':')]
    totalSecs += (timeParts[0] * 60 + timeParts[1]) * 60 + timeParts[2]
totalSecs, sec = divmod(totalSecs, 60)
hr, min = divmod(totalSecs, 60)
print "%d:%02d:%02d" % (hr, min, sec)

Result:

9:31:11
Mike DeSimone
I had this in an array as strings as described..Thanks....
Hulk
+1 just for giving `divmod()` some airplay ... pity nobody was ever brave enough to request GvR to implement `/%` and `/%=` operators ;-) ... read this and weep: `mins, secs /%= 60; hours, mins /%= 60; days, hours /%= 24`
John Machin
@John: I personally find that illegible. You have to remember which thing on the LHS is the input dividend. It also creates a case where an operator returns a tuple, which prevents chaining operations, which is the whole point of binary operators. I find the `divmod` way a *lot* clearer.
Mike DeSimone
A: 

Assuming you want to add up the seconds for a total time:

def parse_time(s):
    hour, min, sec = s.split(':')
    try:
        hour = int(hour)
        min = int(min)
        sec = int(sec)
    except ValueError:
        # handle errors here, but this isn't a bad default to ignore errors
        return 0
    return hour * 60 * 60 + min * 60 + sec

print parse_time('0:00:00') + parse_time('0:00:15') + parse_time('9:30:56')
xyld
A: 

Naive approach (without exception handling):

#!/usr/bin/env python

def sumup(*times):
    cumulative = 0
    for t in times:
        hours, minutes, seconds = t.split(":")
        cumulative += 3600 * int(hours) + 60 * int(minutes) + int(seconds)
    return cumulative

def hms(seconds):
    """Turn seconds into hh:mm:ss"""
    hours = seconds / 3600
    seconds -= 3600*hours
    minutes = seconds / 60
    seconds -= 60*minutes
    return "%02d:%02d:%02d" % (hours, minutes, seconds)

if __name__ == '__main__':
    print hms(sumup(*("0:00:00", "0:00:15", "9:30:56")))
    # will print: 09:31:11
The MYYN
+5  A: 

It depends on the form you have these times in, for example if you already have them as datetime.timedeltas, then you could just sum them up:

>>> s = datetime.timedelta(seconds=0) + datetime.timedelta(seconds=15) + datetime.timedelta(hours=9, minutes=30, seconds=56)
>>> str(s)
'9:31:11'
SilentGhost
I think this is the most correct solution using deltas
dassouki
A: 
lines = ["0:00:00", "0:00:15", "9:30:56"]
total = 0
for line in lines:
    h, m, s = map(int, line.split(":"))
    total += 3600*h + 60*m + s
print "%02d:%02d:%02d" % (total / 3600, total / 60 % 60, total % 60)
Bolo
Ummmm this is tagged `Python` not `awk`; `3600*"0"` won't compute; you need to use `int()`; you need to test stuff before publishing it
John Machin
I've added `map(int`
J.F. Sebastian
@John Oops! You're right.
Bolo