如何在python中使用re从PT格式日期时间中提取分钟和秒

时间:2019-04-21 20:53:47

标签: regex python-3.x

如何从时间格式PT34M23SPT32S中提取分钟和秒,并将它们转换成总秒数?

import re
M= re.compile('[\d]+M')
S= re.compile('[\d]+S')

txt='PT32S'
m=re.compile('[\d]+')
s=re.compile('[\d]+')
if M.findall(txt)!=[]:
    mins=M.findall(txt)
    secs=S.findall(txt)
    mm=m.findall(mins[0])
    ss=s.findall(secs[0])
else:
    ss=s.finall(S.findall(txt)[0])

1 个答案:

答案 0 :(得分:0)

以下是从这些日期格式中提取秒的几个选项。

使用regex

import re

txt = "PT34M23S"
seconds = 0

try:
    seconds += int(re.search(r"(\d+)S$", txt).group(1))
    seconds += int(re.search(r"(\d+)M", txt).group(1)) * 60
except AttributeError:
    pass

print(seconds) # => 2063

使用datetime库:

from datetime import datetime

txt = "PT34M23S"
dt = 0

try:
    dt = datetime.strptime(txt, "PT%MM%SS") 
except ValueError:
    dt = datetime.strptime(txt, "PT%SS") 

seconds = (dt - datetime.strptime("0", "%S")).total_seconds()
print(seconds) # => 2063.0