如何在Python中将H:MM:SS时间字符串转换为秒?
基本上我有这个问题的反面:h:m:s的Python时间秒
我有一个格式为H:MM:SS的字符串(分钟和秒始终为2位数字),我需要它代表的整数秒数。 如何在python中执行此操作?
例如:
“ 1:23:45”将产生5025的输出
“ 0:04:15”将产生255的输出
“ 0:00:25”将产生25的输出
等等
hughes asked 2020-07-13T06:29:33Z
10个解决方案
67 votes
def get_sec(time_str):
"""Get Seconds from time."""
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'))
taskinoor answered 2020-07-13T06:29:44Z
44 votes
t = "1:23:45"
print(sum(int(x) * 60 ** i for i,x in enumerate(reversed(t.split(":")))))
当前示例详细说明:
45 × 60⁰ = 45 × 1 = 45
23 × 60¹ = 23 × 60 = 1380
1 × 60² = 1 × 3600 = 3600
FMc answered 2020-07-13T06:30:04Z
8 votes
使用日期时间模块
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()))
输出:36930
kaush answered 2020-07-13T06:30:28Z
2 votes
您可以使用lambda并减少列表以及m = 60s和h = 60m的事实。 (请参阅[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(',')])
scavara answered 2020-07-13T06:30:48Z
2 votes
您可以将时间分为一个列表,然后添加每个单独的时间部分,将小时部分乘以3600(一小时的秒数),将分钟部分乘以60(一分钟的秒数),例如:
timeInterval ='00:35:01'
list = timeInterval.split(':')
hours = list[0]
minutes = list[1]
seconds = list[2]
total = (int(hours) * 3600 + int(minutes) * 60 + int(seconds))
print("total = ", total)
raviGupta answered 2020-07-13T06:31:08Z
1 votes
parts = time_string.split(":")
seconds = int(parts[0])*(60*60) + int(parts[1])*60 + int(parts[2])
DaClown answered 2020-07-13T06:31:23Z
1 votes
无需进行很多检查,并假设它是“ SS”或“ MM:SS”或“ HH:MM:SS”(尽管不一定每个部分两位):
def to_seconds(timestr):
seconds= 0
for part in timestr.split(':'):
seconds= seconds*60 + int(part)
return seconds
这是FMc答案的不同“拼写” :)
tzot answered 2020-07-13T06:31:48Z
1 votes
我真的不喜欢任何给定的答案,因此我使用了以下内容:
def timestamp_to_seconds(t):
return sum(float(n) * m for n,
m in zip(reversed(time.split(':')), (1, 60, 3600))
)
Nathan Rice answered 2020-07-13T06:32:09Z
0 votes
如果您对字符串有几天的话,另一种选择是:
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])
Italux answered 2020-07-13T06:32:28Z
0 votes
扩展体现了Horner方法一半的@FMc解决方案。 Horner方法的优点:跳过反向列表,避免计算功率。
from functools import reduce
timestamp = "1:23:45"
reduce(lambda sum, d: sum * 60 + int(d), timestamp.split(":"), 0)
Bernhard Wagner answered 2020-07-13T06:32:49Z