在python中将时间字符串转换为秒
我需要将以下格式的时间值字符串转换为秒。我正在使用time.strptime('00:00:00,000','%I:%M:%S')
例如:
1.'00:00:00,000' -> 0 seconds
2.'00:00:10,000' -> 10 seconds
3.'00:01:04,000' -> 64 seconds
4. '01:01:09,000' -> 3669 seconds
我是否需要使用正则表达式来执行此操作?我尝试使用时间模块,但抛出了time.strptime('00:00:00,000','%I:%M:%S')
ValueError: time data '00:00:00,000' does not match format '%I:%M:%S'
有人可以告诉我如何解决吗?
编辑:
我认为
pt =datetime.datetime.strptime(timestring,'%H:%M:%S,%f')
total_seconds = pt.second+pt.minute*60+pt.hour*3600
给出正确的值..我使用了错误的模块
damon asked 2020-07-13T23:20:53Z
8个解决方案
56 votes
对于Python 2.7:
>>> import datetime
>>> import time
>>> x = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')
>>> datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()
60.0
Burhan Khalid answered 2020-07-13T23:21:06Z
30 votes
我认为将是更多的pythonic方式:
timestr = '00:04:23'
ftr = [3600,60,1]
sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])
输出为263秒。
我很想知道是否有人可以进一步简化它。
user1721943 answered 2020-07-13T23:21:35Z
18 votes
没有进口
time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":")))
thafritz answered 2020-07-13T23:21:55Z
5 votes
要获得.total_seconds(),您应该减去1900-01-01:
>>> from datetime import datetime
>>> datetime.strptime('01:01:09,000', '%H:%M:%S,%f')
datetime.datetime(1900, 1, 1, 1, 1, 9)
>>> td = datetime.strptime('01:01:09,000', '%H:%M:%S,%f') - datetime(1900,1,1)
>>> td
datetime.timedelta(0, 3669)
>>> td.total_seconds() # 2.7+
3669.0
以上.total_seconds()表示输入少于一天,支持时差超过一天:
>>> import re
>>> from datetime import timedelta
>>> td = timedelta(**dict(zip("hours minutes seconds milliseconds".split(),
... map(int, re.findall('\d+', '31:01:09,000')))))
>>> td
datetime.timedelta(1, 25269)
>>> td.total_seconds()
111669.0
您在Python 2.6上模拟了.total_seconds():
>>> from __future__ import division
>>> ((td.days * 86400 + td.seconds) * 10**6 + td.microseconds) / 10**6
111669.0
jfs answered 2020-07-13T23:22:23Z
4 votes
看来您愿意舍弃几分之一秒...问题是您不能在%I中使用“ 00”作为小时
>>> time.strptime('00:00:00,000'.split(',')[0],'%H:%M:%S')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>>
Mike Pennington answered 2020-07-13T23:22:43Z
3 votes
总是有手工解析
>>> import re
>>> ts = ['00:00:00,000', '00:00:10,000', '00:01:04,000', '01:01:09,000']
>>> for t in ts:
... times = map(int, re.split(r"[:,]", t))
... print t, times[0]*3600+times[1]*60+times[2]+times[3]/1000.
...
00:00:00,000 0.0
00:00:10,000 10.0
00:01:04,000 64.0
01:01:09,000 3669.0
>>>
Nick Craig-Wood answered 2020-07-13T23:23:03Z
2 votes
import time
from datetime import datetime
t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())
结果: 3.0
Soheil Karshenas answered 2020-07-13T23:23:23Z
0 votes
受到sverrir-sigmundarson的评论的启发:
def time_to_sec(time_str):
return sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time_str.split(":"))))
YScharf answered 2020-07-13T23:23:43Z