Python summing up time

后端 未结 9 1674
后悔当初
后悔当初 2020-12-06 00:55

In python how do I sum up the following time?

 0:00:00
 0:00:15
 9:30:56
相关标签:
9条回答
  • 2020-12-06 01:11
    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 讨论(0)
  • 2020-12-06 01:21
    from datetime import timedelta
    
    h = ['3:00:00','1:07:00', '4:00:00', '4:05:00', '4:10:00', '4:03:00']
    
    def to_td(h):
        ho, mi, se = h.split(':')
        return timedelta(hours=int(ho), minutes=int(mi), seconds=int(se))
    
    print(str(sum(map(to_td, h), timedelta())))
    
    # Out[31]: 20:25:00
    
    0 讨论(0)
  • 2020-12-06 01:22

    Naive approach (without exception handling):

    #!/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
    
    0 讨论(0)
提交回复
热议问题