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

hug*_*hes 45 python

基本上我有这个问题的反面:Python时间秒到h:m:s

我有一个格式为H:MM:SS的字符串(总是2位数分钟和秒),我需要它所代表的整数秒数.我怎么能在python中这样做?

例如:

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

等等

tas*_*oor 69

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'))
Run Code Online (Sandbox Code Playgroud)


FMc*_*FMc 44

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

目前的例子,详细阐述:

    45 × 60? = 45 ×    1 =   45
    23 × 60¹ = 23 ×   60 = 1380
     1 × 60² =  1 × 3600 = 3600
Run Code Online (Sandbox Code Playgroud)

  • 这个优秀的代码也将正确处理`s`和`m:s`字符串,如"53"和"2:41" (2认同)
  • 这很棒。将“int(x)”更改为“float(x)”,它将处理十进制秒,而且它不需要小时的前导零。VTT 时间戳省略前导 0 小时,直到小时 > 1。 (2认同)

kau*_*ush 8

使用正则表达式和日期时间模块

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()))
Run Code Online (Sandbox Code Playgroud)

产量:36930


Dan*_*eba 6

使用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()
Run Code Online (Sandbox Code Playgroud)

datetime.strptime根据格式 %H:%M:%S 解析字符串,并创建一个日期时间对象,为年 1900 年、月 1、日 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
Run Code Online (Sandbox Code Playgroud)


tzo*_*zot 5

没有很多检查,并假设它是“SS”或“MM:SS”或“HH:MM:SS”(尽管每个部分不一定是两位数):

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

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

  • 这是这里最好的解决方案。怎么票数这么少啊!它在一个简洁的单一函数中考虑缺少“分钟”或“小时”部分的字符串,并且不使用任何额外的库。荣誉! (2认同)