繁体   English   中英

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

[英]How to convert an H:MM:SS time string to seconds in Python?

基本上我有这个问题的反面: Python Time Seconds to h:m:s

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

例如:

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

等等

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'))
ts = '1:23:45'
secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(ts.split(':'))))
print(secs)

使用日期时间模块

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

没有很多检查,并假设它是“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 答案的不同“拼写” :)

使用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 解析字符串,并创建一个 datetime 对象为 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

您可以使用 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(',')])

您可以将时间拆分为一个列表并添加每个单独的时间分量,将小时分量乘以 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)

对于 %H:%M:%S.%f

def get_sec(time_str):
    h, m, s = time_str.split(':')
    return int(h) * 3600 + int(m) * 60 + float(s)

我真的不喜欢任何给定的答案,所以我使用了以下内容:

def timestamp_to_seconds(t):
    return sum(float(n) * m for n,
               m in zip(reversed(time.split(':')), (1, 60, 3600))
               )
parts = time_string.split(":")
seconds = int(parts[0])*(60*60) + int(parts[1])*60 + int(parts[2])

如果您在字符串上有几天,另一种选择:

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

扩展@FMc 的解决方案,该解决方案体现了霍纳方法的一半。 Horner 方法的优点:跳过反转列表,避免功率计算。

from functools import reduce

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

只是对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 

在 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']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM