如何从时间格式PT34M23S
或PT32S
中提取分钟和秒,并将其转换为总秒数?
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])
参考方案
这是从这些日期格式中提取秒的几个选项。
使用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
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
查找字符串中的行数 - python我正在创建一个python电影播放器/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或可以编写代码的函数来做到这一点:x = """ line1 line2 """ getLines(x) python大神给出的解决方案 如果换行符是'\n',则nlines …
字符串文字中的正斜杠表现异常 - python为什么S1和S2在撇号位置方面表现不同?S1="1/282/03/10" S2="4/107/03/10" R1="".join({"N\'" ,S1,"\'" }) R2="".join({"N\'…