我有一个文档,其中包含几个我想要求平均值的时间测量值,因此我将分钟和秒转换为总秒数。该文件如下所示:
Boring text
time 15:07现在,我可以通过以下几点来实现:
if line.startswith('time') :
rtminutes = re.findall('([0-9][0-9]):', line)
for min in rtminutes :
rtmintosec = float(min) * 60
rtseconds = re.findall(':([0-9][0-9])', line)
for sec in rtseconds :
totsecs = rtmintosec + float(sec)
print ("Total roast time in seconds:", totsecs)似乎更好的方法是使用时间和total_seconds。
import time
if line.startswith('time') :
rt = re.search('\d{2}:\d{2}', line)
rtime = time.strftime(rt, '%M:%S')
rtime.total_seconds()每次我尝试一种时间方法时,我都会得到如下的错误:
TypeError: strftime() argument 1 must be str, not re.Match很明显我错过了什么地方的船。感谢您的建议。
发布于 2020-08-30 02:38:55
您需要确保找到匹配的字符串,如果是,则从re.Match对象中提取匹配的字符串。
rt = re.search('\d{2}:\d{2}', line)
if rt: # if rt is None then rt.group() will raise an exception
rtime = time.strftime(rt.group(), '%M:%S')
rtime.total_seconds()发布于 2020-08-30 04:17:37
嗨,我用这段代码进行了测试,我刚刚删除了\n,它对我很有效
#line is your line number where the tims is time 15:07
#Boringtext is the file name
from colorama import Fore, Style
import linecache as s
import time
from datetime import timedelta
from datetime import datetime
def file_len(fname , line):
return s.getline(fname,line)
line = file_len('Boringtext',2)
if line.startswith('time') :
rt = line.split(' ')
rtime = datetime.strptime(rt[1].rstrip("\n"), '%M:%S')
t = timedelta(minutes = rtime.minute , seconds = rtime.second )
print(Fore.BLUE,t.total_seconds(),Style.RESET_ALL)https://stackoverflow.com/questions/63650532
复制相似问题