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

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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 need the integer number of seconds that it represents. How can I do this in python?

For example:

  • "1:23:45" would produce an output of 5025
  • "0:04:15" would produce an output of 255
  • "0:00:25" would produce an output of 25

etc

回答1:

def get_sec(time_str):     h, m, s = time_str.split(':')     return int(h) * 3600 + int(m) * 60 + int(s)  print get_sec('1:23:45') print get_sec('0:04:15') print get_sec('0:00:25') 


回答2:

t = "1:23:45" print(sum(int(x) * 60 ** i for i,x in enumerate(reversed(t.split(":"))))) 

The current example, elaborated:



回答3:

Use regular expressions and datetime module

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

Output: 36930



回答4:

parts = time_string.split(":") seconds = int(parts[0])*(60*60) + int(parts[1])*60 + int(parts[2]) 


回答5:

Without many checks, and assuming it's either "SS" or "MM:SS" or "HH:MM:SS" (although not necessarily two digits per part):

def to_seconds(timestr):     seconds= 0     for part in timestr.split(':'):         seconds= seconds*60 + int(part)     return seconds 

This is a different “spelling” of FMc's answer :)



回答6:

You can use lambda and reduce a list and the fact that m=60s and h=60m. (see "Reducing a List" at http://www.python-course.eu/lambda.php)

timestamp = "1:23:45" seconds = reduce(lambda x, y: x*60+y, [int(i) for i in (timestamp.replace(':',',')).split(',')]) 


回答7:

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]) 


回答8:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!