我如何将所有元素加在一起组成一个由时间组成的数组

时间:2019-07-05 13:28:55

标签: python time sum

我有一个用字符串填充的数组,这些字符串表示时间元素,而我试图从该数组中获取总时间。


testArray=['02:30:57','15:09:18','01:00:18']
def arraysum(x): 
  if (len(x)%2==0):

     for i in range (0,len(x)-1,2):
            for j in range (1,len(x),2) :
                time2=datetime.strptime(x[i],"%H:%M:%S")
                time1=datetime.strptime(x[j],"%H:%M:%S")
                time1delta=timedelta(hours=time1.hour, minutes=time1.minute, seconds=time1.second)
                time2delta=timedelta(hours=time2.hour, minutes=time2.minute, seconds=time2.second)
                total=time2delta+time1delta
                print (total)


    else:
        for i in range (0,len(x),2):
            for j in range (1,len(x)-1,2) :
                time2=datetime.strptime(x[i],"%H:%M:%S")
                time1=datetime.strptime(x[j],"%H:%M:%S")
                time1delta=timedelta(hours=time1.hour, minutes=time1.minute, seconds=time1.second)
                time2delta=timedelta(hours=time2.hour, minutes=time2.minute, seconds=time2.second)
                total=time2delta+time1delta
                print (total)


arraysum(testArray)

这是我得到的输出,这是不正确的。 17:40:15 16:09:36

我需要显示18:40:15

3 个答案:

答案 0 :(得分:2)

使用datetime模块。使用datetime.timedelta来增加时间。

例如:

import datetime

testArray=['02:30:57','15:09:18','01:00:18'] 
result = None
for d in testArray:
    if not result:
        result = datetime.datetime.strptime(d, "%H:%M:%S")
    else:
        value = datetime.datetime.strptime(d, "%H:%M:%S")
        result = result + datetime.timedelta(hours=value.hour, minutes=value.minute, seconds=value.second)

print(result.strftime("%H:%M:%S")) #-->18:40:33

答案 1 :(得分:1)

这是另一种方式:

from datetime import timedelta


def f(t):
    result = timedelta()
    for i in t:
        hours, minutes, seconds = i.split(":")
        result += timedelta(
            hours=int(hours), minutes=int(minutes), seconds=int(seconds)
        )
    return result


test = ['02:30:57','15:09:18', '01:00:18']
print(f(test))
# result = 18:40:33

答案 2 :(得分:0)

如果您愿意使用大熊猫,那么结果会变得容易得多,因为大熊猫具有很多功能,可以将st解析为更丰富的时间对象。

import pandas as pd

testArray=['02:30:57','15:09:18','01:00:18']
total_time = sum((pd.Timedelta(t) for t in testArray), pd.Timedelta(0, 's'))

要打印,您有几种选择。 str(total_time)返回'0 days 18:40:33'total_time.isoformat()返回'P0DT18H40M33S',而repr(total_time)返回"Timedelta('0 days 18:40:33')"

如果您不想使用熊猫,可以做一些辅助功能。

import datetime

testArray=['02:30:57','15:09:18','01:00:18']

def parse_timedelta_string(timedelta_string):
    hours, minutes, seconds = map(int, timedelta_string.split(':'))
    return datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)

total_time = sum((parse_timedelta_string(t) for t in testArray), datetime.timedelta(seconds=0))

print(total_time)