【问题标题】:How to add time in a python list如何在python列表中添加时间
【发布时间】:2017-01-06 16:21:31
【问题描述】:

这是列表:

lsty = ['1:07:11', '2:37:28', '07:11', '1:07:11']

时间可以是“2:37:28”(2h 37m 28s)或“07:11”(7m 11s)。我该如何总结这份清单?

【问题讨论】:

  • 你做过研究吗?
  • @Alex.S 是的。我找到了这个link。但是当时间采用这种格式时,它会总结为 h:m:s

标签: python-2.7


【解决方案1】:

您可能会发现原生 python datetime.timedelta 对象很有用,它允许您以 Python 理解的方式表示时间,并与其他 timedelta 对象执行算术运算。

也许是这样的?这是完全未经测试的:

from datetime import timedelta
def sum_times(times):
    sum = timedelta(0)
    for time in times:
        time_split = time.split(':')  # Extract just time vals
        if len(time_split) == 2:  # Just mins/secs
            t_delt = timedelta(minutes=time_split[0],
                               seconds=time_split[1])
        else: 
            t_delt = timedelta(hours=time_split[0],
                               minutes=time_split[1],
                               seconds=time_split[2])
        sum += t_delt  # This is where the magic happens
    return '%s:%s:%s' % (sum.hours, sum.minutes, sum.seconds)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 2021-03-20
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多