Python resumiendo el tiempo

En Python, ¿cómo resumo la siguiente vez?

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

Como una lista de cuerdas?

 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) 

Resultado:

 9:31:11 

Depende de la forma en que tengas estos tiempos, por ejemplo, si ya los tienes como datetime.timedelta s, entonces podrías resumirlos:

 >>> s = datetime.timedelta(seconds=0) + datetime.timedelta(seconds=15) + datetime.timedelta(hours=9, minutes=30, seconds=56) >>> str(s) '9:31:11' 

Usando timedeltas (probado en Python 3.4):

 import datetime timeList = ['0:00:00', '0:00:15', '9:30:56'] sum = datetime.timedelta() for i in timeList: (h, m, s) = i.split(':') d = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)) sum += d print(str(sum)) 

Resultado:

 9:31:11 

Estoy realmente decepcionado si no hay más solución pythonic … 🙁

Horrible ->

 timeList = [ '0:00:00', '0:00:15', '9:30:56' ] ttt = [map(int,i.split()[-1].split(':')) for i in timeList] seconds=reduce(lambda x,y:x+y[0]*3600+y[1]*60+y[2],ttt,0) #seconds == 34271 

Este también se ve horrible ->

 zero_time = datetime.datetime.strptime('0:0:0', '%H:%M:%S') ttt=[datetime.datetime.strptime(i, '%H:%M:%S')-zero_time for i in timeList] delta=sum(ttt,zero_time)-zero_time # delta==datetime.timedelta(0, 34271) # str(delta)=='9:31:11' # this seems good, but # if we have more than 1 day we get for example str(delta)=='1 day, 1:05:22' 

Realmente frustrante es también esto ->

 sum(ttt,zero_time).strftime('%H:%M:%S') # it is only "modulo" 24 :( 

Realmente me gusta ver una frase así que traté de hacer una en python3: P (buen resultado pero aspecto horrible)

 import functools timeList = ['0:00:00','0:00:15','9:30:56','21:00:00'] # notice additional 21 hours! sum_fnc=lambda ttt:(lambda a:'%02d:%02d:%02d' % (divmod(divmod(a,60)[0],60)+(divmod(a,60)[1],)))((lambda a:functools.reduce(lambda x,y:x+y[0]*3600+y[1]*60+y[2],a,0))((lambda a:[list(map(int,i.split()[-1].split(':'))) for i in a])(ttt))) # sum_fnc(timeList) -> '30:40:11' 

Suponiendo que desea sumr los segundos por un tiempo total:

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

Enfoque ingenuo (sin manejo de excepciones):

 #!/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 

Bellow es una solución usando lista de comprensión:

 from datetime import timedelta def time_sum(time: List[str]) -> timedelta: """ Calculates time from list of time hh:mm:ss format """ return sum( [ timedelta(hours=int(ms[0]), minutes=int(ms[1]), seconds=int(ms[2])) for t in time for ms in [t.split(":")] ], timedelta(), ) 

Ejemplo:

 time_list = ["0:00:00", "0:00:15", "9:30:56"] total = time_sum(time_list) print(f"Total time: {total}")