基本上我有这个问题的反面:Python时间秒到h:m:s
我有一个格式为H:MM:SS的字符串(总是2位数分钟和秒),我需要它所代表的整数秒数.我怎么能在python中这样做?
例如:
等等
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)
使用正则表达式和日期时间模块
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
使用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)
没有很多检查,并假设它是“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 答案的不同“拼写” :)