2010-05-06 65 views
8

在Python中我如何总结下面的时间?Python总结时间

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

要从0:00:00加起来的差别我猜?即三角洲,而不是实际时间? – 2010-05-06 12:12:14

+0

@steve:好了,deltas加起来就是'9:30:56' – SilentGhost 2010-05-06 12:13:35

+0

我使用的是python 2.4,我不能使用strptime,是的,我想加上deltas,对于上面提到的例子,答案应该是9 :31:11 – Hulk 2010-05-06 12:18:12

回答

9

作为字符串列表?

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) 

结果:

9:31:11 
+0

我有这个数组作为字符串描述..谢谢.... – Hulk 2010-05-06 12:36:00

+0

+1只是为了给'divmod()'一些airplay ...可惜没有人曾勇敢地要求GvR实现'/%'和'/%='运算符;-) ...读这个并且哭泣:'mins,secs /%= 60;小时,分钟/%= 60;天,小时/%= 24' – 2010-05-06 12:54:35

+4

@John:我个人觉得难以辨认。你必须记住LHS上的哪些东西是投入的红利。它还创建了一个操作符返回一个元组的操作,该操作可以防止链式操作,这是二元操作符的全部要点。我发现'divmod'的方式非常清晰。 – 2010-05-06 18:55:52

2

假设你想添加了秒的总时间:

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

幼稚的做法(无异常处理):

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

这取决于你有这些时间的形式,例如,如果你已经有了他们为datetime.timedelta S,那么你可以只总结起来:

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

我认为这是使用deltas最正确的解决方案 – dassouki 2010-05-06 12:21:22

2
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) 
+0

嗯,它被标记为'Python' not'awk'; '3600 *“0”'不会计算;你需要使用'int()';你需要在发布之前测试东西 – 2010-05-06 12:33:48

+0

我已经添加了'map(int' – jfs 2010-05-06 12:49:08

+0

@John Oops!你是对的 – Bolo 2010-05-06 12:59:34

5

我真的很失望,如果没有任何更Python的解决方案... :(

可怕的一个 - >

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 

这一个看起来可怕太 - >

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' 

很无奈也在于此 - >

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

我真的想看到一个班轮所以,我试图让一个在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' 
8

使用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)) 

结果:

9:31:11 
+0

也可以在2.7中工作,因为代码可读性强,直观 – adelval 2015-06-19 05:34:23

0

贝娄是使用的解决方案减少和列表理解:

from functools import reduce 
from datetime import timedelta 

time_list = ['0:00:00', '0:00:15', '9:30:56'] 

total = reduce(lambda x, y: x + y, 
     [timedelta(hours=int(ms[0]), minutes=int(ms[1]), seconds=int(ms[2])) 
      for t in time_list 
       for ms in [t.split(':')]]) 

print(f'Total time: {total}') 

总时间:9时31分11秒