How to convert an H:MM:SS time string to seconds in Python?

前端 未结 12 1765
陌清茗
陌清茗 2020-11-29 22:14

Basically I have the inverse of this problem: Python Time Seconds to h:m:s

I have a string in the format H:MM:SS (always 2 digits for minutes and seconds), and I nee

12条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 22:39

    Another alternative if you have days on string:

    def duration2sec(string):
        if "days" in string:
            days = string.split()[0]
            hours = string.split()[2].split(':')
            return int(days) * 86400 + int(hours[0]) * 3600 + int(hours[1]) * 60 + int(hours[2])
        else:
            hours = string.split(':')
            return int(hours[0]) * 3600 + int(hours[1]) * 60 + int(hours[2])
    

提交回复
热议问题