Python summing up time

后端 未结 9 1676
后悔当初
后悔当初 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 00:59

    Bellow is a solution using list comprehension:

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

    Example:

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

提交回复
热议问题