【发布时间】:2011-09-18 04:05:49
【问题描述】:
基本上我有这个问题的反面:Python Time Seconds to h:m:s
我有一个格式为 H:MM:SS 的字符串(分钟和秒总是 2 位数字),我需要它表示的整数秒数。我如何在 python 中做到这一点?
例如:
- "1:23:45" 将产生 5025 的输出
- "0:04:15" 将产生 255 的输出
- "0:00:25" 将产生 25 的输出
等
【问题讨论】:
标签: python
基本上我有这个问题的反面:Python Time Seconds to h:m:s
我有一个格式为 H:MM:SS 的字符串(分钟和秒总是 2 位数字),我需要它表示的整数秒数。我如何在 python 中做到这一点?
例如:
等
【问题讨论】:
标签: python
扩展@FMc 的解决方案,它体现了Horner's method 的一半。霍纳法的优点:跳过倒序,避免power计算。
from functools import reduce
timestamp = "1:23:45"
seconds = reduce(lambda s, d: s * 60 + int(d), timestamp.split(":"), 0)
或者,如果你不喜欢 reduce(as does Guido van Rossum 和 @0xc0de below):
timestamp = "1:23:45"
seconds = 0
for d in timestamp.split(":"):
seconds = seconds * 60 + int(d)
如果您更喜欢zip(@nathan-rice below 也是如此):
from itertools import accumulate, repeat
from operator import mul
def timestamp_to_seconds(t):
return sum(int(n) * m for n, m in
zip(reversed(t.split(":")), accumulate(repeat(60), func=mul, initial=1)))
【讨论】:
reduced 的可读性。 +1 对于这些情况,我不是 reduce() 的粉丝,我更愿意避免这些。
对于 %H:%M:%S.%f
def get_sec(time_str):
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + float(s)
【讨论】:
没有太多检查,假设它是“SS”或“MM:SS”或“HH:MM:SS”(虽然不一定每个部分两位数):
def to_seconds(timestr):
seconds= 0
for part in timestr.split(':'):
seconds= seconds*60 + int(part, 10)
return seconds
>>> to_seconds('09')
9
>>> to_seconds('2:09')
129
>>> to_seconds('1:02:09')
3729
这是 FMc 答案的不同“拼写”:)
【讨论】:
minutes 或hours 部分的字符串考虑在一个简洁的单一函数中,并且不使用任何额外的库。赞一个!
在 Pandas 中使用 @JayRizzo 的酷函数和列表理解:
def get_sec(time_str):
"""Get Seconds from time."""
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + int(s)
df['secs']=[get_sec(x) for x in df['original_time_string']]
【讨论】:
只是对taskinoor的热烈响应的简单概括
就我的问题而言,格式类似,但包括 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
【讨论】:
ts = '1:23:45'
secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(ts.split(':'))))
print(secs)
【讨论】:
s和m:s字符串,比如“53”和“2:41”
使用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.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
【讨论】:
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'))
【讨论】:
我不太喜欢给出的任何答案,所以我使用了以下答案:
def timestamp_to_seconds(t):
return sum(float(n) * m for n,
m in zip(reversed(time.split(':')), (1, 60, 3600))
)
【讨论】:
使用日期时间模块
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
【讨论】:
re。字符串有一个拆分方法:str.split()。使用 t.split(':') 而不是 re.split(':', t) 会更干净。
h, m, s = [int(x) for x in t.split(':')]。
您可以将时间拆分为一个列表并添加每个单独的时间分量,将小时分量乘以 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)
【讨论】:
您可以使用 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(',')])
【讨论】:
如果你有几天的字符串,另一种选择:
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])
【讨论】:
else 部分会做到这一点。但我同意越简单越好。
parts = time_string.split(":")
seconds = int(parts[0])*(60*60) + int(parts[1])*60 + int(parts[2])
【讨论】: