Python总结时间

Hul*_*ulk 11 python datetime

在python中我如何总结以下时间?

 0:00:00
 0:00:15
 9:30:56
Run Code Online (Sandbox Code Playgroud)

Sil*_*ost 26

这取决于你有这些时间的形式,例如,如果你已经将它们作为datetime.timedeltas,那么你可以总结它们:

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

  • 我认为这是使用增量的最正确的解决方案 (2认同)

Joh*_*hny 14

使用timedeltas(在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))
Run Code Online (Sandbox Code Playgroud)

结果:

9:31:11
Run Code Online (Sandbox Code Playgroud)


Mik*_*one 11

作为字符串列表?

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)
Run Code Online (Sandbox Code Playgroud)

结果:

9:31:11
Run Code Online (Sandbox Code Playgroud)

  • @John:我个人觉得难以辨认.你必须记住LHS上的哪一项是输入红利.它还创建了一个操作符返回元组的情况,这会阻止链接操作,这是二元运算符的重点.我觉得`divmod`的方式很清楚. (4认同)

Lis*_*iso 5

如果没有更多的pythonic解决方案,我真的很失望...... :(

可怕的 - >

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
Run Code Online (Sandbox Code Playgroud)

这个看起来也很可怕 - >

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'
Run Code Online (Sandbox Code Playgroud)

真的很令人沮丧的是 - >

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

我真的很喜欢看单行,所以我试着在python3中制作一个:P(效果很好,但看起来很可怕)

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'
Run Code Online (Sandbox Code Playgroud)