可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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))