如何在Python中将H:MM:SS时间字符串转换为秒?

如何在Python中将H:MM:SS时间字符串转换为秒?,python,Python,基本上我得到了这个问题的相反结果: 我有一个格式为H:MM:SS的字符串(分和秒总是2位数),我需要它表示的整数秒数。如何在python中实现这一点 例如: “1:23:45”将产生5025的输出 “0:04:15”将产生255的输出 “0:00:25”将产生25的输出 etcdef获取秒(时间): “”“从时间中获取秒数。”“” h、 m,s=时间分割(':') 返回整数(h)*3600+整数(m)*60+整数(s) 打印(获取秒('1:23:45')) 打印(获取秒('0:04:15')

基本上我得到了这个问题的相反结果:

我有一个格式为H:MM:SS的字符串(分和秒总是2位数),我需要它表示的整数秒数。如何在python中实现这一点

例如:

  • “1:23:45”将产生5025的输出
  • “0:04:15”将产生255的输出
  • “0:00:25”将产生25的输出
etc

def获取秒(时间):
“”“从时间中获取秒数。”“”
h、 m,s=时间分割(':')
返回整数(h)*3600+整数(m)*60+整数(s)
打印(获取秒('1:23:45'))
打印(获取秒('0:04:15'))
打印(获取秒('0:00:25'))

无需多次检查,并假设它是“SS”或“MM:SS”或“HH:MM:SS”(虽然每个零件不一定有两个数字):

这是FMc答案的不同“拼写:)

使用日期时间模块

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

如果字符串上有天数,则另一种选择:

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

您可以使用lambda并减少一个列表以及m=60s和h=60m这一事实。(参见第页的“减少列表”)


我真的不喜欢给出的任何答案,因此我使用了以下方法:

def时间戳到秒(t):
返回和(浮动(n)*m表示n,
拉链中的m(反转(时间分割(':'),(1,60,3600))
)

您可以将时间拆分为一个列表,并添加每个单独的时间分量,将小时分量乘以3600(一小时的秒数),将分钟分量乘以60(一分钟的秒数),如:


扩展@FMc的解决方案,该解决方案包含了。霍纳方法的优点:跳过列表反转,避免计算

from functools import reduce

timestamp = "1:23:45"
reduce(lambda sum, d: sum * 60 + int(d), timestamp.split(":"), 0)

使用
datetime
模块也是可行的,而且更加健壮

import datetime as dt

def get_total_seconds(stringHMS):
   timedeltaObj = dt.datetime.strptime(stringHMS, "%H:%M:%S") - dt.datetime(1900,1,1)
   return timedeltaObj.total_seconds()
datetime.strtime
根据格式%H:%M:%S解析字符串,并创建日期时间对象,如1900年、月1日、小时H、分钟M和秒S

这就是为什么要减去年、月和日,就必须得到秒的总数

print(get_total_seconds('1:23:45'))
>>> 5025.0

print(get_total_seconds('0:04:15'))
>>> 255.0

print(get_total_seconds('0:00:25'))
>>>25.0

这只是一个对

在我的问题背景下,格式类似,但包括AM或PM

格式为“HH:MM:SS AM”或“HH:MM:SS PM”

在这种情况下,功能更改为:

def get_sec(time_str):
"""Get Seconds from time."""
if 'AM' in time_str:
    time_str = time_str.strip('AM')
    h, m, s = time_str.split(':')
    seconds = int(h) * 3600 + int(m) * 60 + int(s)
if 'PM' in time_str:
    time_str = time_str.strip('PM')
    h, m, s = time_str.split(':')
    seconds = (12 + int(h)) * 3600 + int(m) * 60 + int(s)

return seconds 

可能是几乎工作的重复,我不得不使用int(…)作为taskino或建议它正常工作。这是一个非常有趣的技术。谢谢分享。那个双星操作符是做什么的?@hughes求幂运算。这个高级代码也能正确处理
s
m:s
字符串,比如“53”和“2:41”。在OP的示例输入下,代码的输出是什么样子的?你不需要
re
。字符串具有拆分方法:
str.split()
。使用
t.split(“:”)
而不是
re.split(“:”,t)
要干净得多。我最终使用了这个解决方案,因为它似乎是最标准的方法。我使用理解列表稍微修改了h,m,s到int的转换,以使转换行更清晰,结果如下:
h,m,s=[int(x)for x in t.split(“:”)]
。问题是将h:MM:SS时间字符串转换为秒,而不是将天转换为秒。请尝试改写您的问题答案示例是功能性的,
否则
部分将完成此操作。但是我同意越简单越好。真的很有用。谢谢我喜欢您考虑只包含秒或分钟的较短字符串。。。这是最好的解决方案。为什么投票率这么低!?它在一个简洁、单一的函数中考虑缺少
minutes
hours
部分的字符串,并且不使用任何额外的库。荣誉这对我有用。我使用“%H:%M:%S.%f”来处理十进制秒数
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)
from functools import reduce

timestamp = "1:23:45"
reduce(lambda sum, d: sum * 60 + int(d), timestamp.split(":"), 0)
import datetime as dt

def get_total_seconds(stringHMS):
   timedeltaObj = dt.datetime.strptime(stringHMS, "%H:%M:%S") - dt.datetime(1900,1,1)
   return timedeltaObj.total_seconds()
print(get_total_seconds('1:23:45'))
>>> 5025.0

print(get_total_seconds('0:04:15'))
>>> 255.0

print(get_total_seconds('0:00:25'))
>>>25.0
def get_sec(time_str):
"""Get Seconds from time."""
if 'AM' in time_str:
    time_str = time_str.strip('AM')
    h, m, s = time_str.split(':')
    seconds = int(h) * 3600 + int(m) * 60 + int(s)
if 'PM' in time_str:
    time_str = time_str.strip('PM')
    h, m, s = time_str.split(':')
    seconds = (12 + int(h)) * 3600 + int(m) * 60 + int(s)

return seconds