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

前端 未结 12 1749
陌清茗
陌清茗 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:29

    Using datetime module

    import datetime
    t = '10:15:30'
    h,m,s = t.split(':')
    print(int(datetime.timedelta(hours=int(h),minutes=int(m),seconds=int(s)).total_seconds()))
    

    Output: 36930

    0 讨论(0)
  • 2020-11-29 22:30
    parts = time_string.split(":")
    seconds = int(parts[0])*(60*60) + int(parts[1])*60 + int(parts[2])
    
    0 讨论(0)
  • 2020-11-29 22:30

    I didn't really like any of the given answers, so I used the following:

    def timestamp_to_seconds(t):
        return sum(float(n) * m for n,
                   m in zip(reversed(time.split(':')), (1, 60, 3600))
                   )
    
    0 讨论(0)
  • 2020-11-29 22:36
    ts = '1:23:45'
    secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(ts.split(':'))))
    print(secs)
    
    0 讨论(0)
  • 2020-11-29 22:37

    Expanding on @FMc's solution which embodies half of Horner's method. Advantage of Horner's method: Skip reversing the list, avoid power calculation.

    from functools import reduce
    
    timestamp = "1:23:45"
    reduce(lambda sum, d: sum * 60 + int(d), timestamp.split(":"), 0)
    
    0 讨论(0)
  • 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])
    
    0 讨论(0)
提交回复
热议问题