Python总结时间

时间:2010-05-06 12:03:48

标签: python datetime

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

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

8 个答案:

答案 0 :(得分:23)

这取决于您有这些时间的形式,例如,如果您已经将它们作为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'

答案 1 :(得分:12)

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

答案 2 :(得分: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)

结果:

9:31:11

答案 3 :(得分: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

这个看起来很可怕 - >

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'

答案 4 :(得分: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')

答案 5 :(得分: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)

答案 6 :(得分: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

答案 7 :(得分:0)

Bellow是使用列表理解的解决方案:

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(),
    )

示例:

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