Python summing up time

后端 未结 9 1699
后悔当初
后悔当初 2020-12-06 00:55

In python how do I sum up the following time?

 0:00:00
 0:00:15
 9:30:56
9条回答
  •  一个人的身影
    2020-12-06 01:00

    I'm really disappointed if there is not any more pythonic solution... :(

    Horrible one ->

    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
    

    This one looks horrible too ->

    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'
    

    Really frustrating is also this ->

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

    I really like to see one-liner so, I tried to make one in python3 :P (good result but horrible look)

    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'
    

提交回复
热议问题