我目前正在用Python进行一个项目(必须自学Python,目前还在学习Python),该项目从给我的csv文件中获取数据。
目前,我一直在讨论如何循环列表,将字符串从"2小时5分钟15秒“等列表转换为十进制,并将其保存为另一个列表/数组。
我知道H:M:S,但在列表的某些区域,它只是“8分4秒”,所以它从一个小时数到只有几分钟和秒不等。
发布于 2016-05-27 04:04:42
有多个选项可以解析这些时间字符串。这里有一种方法(可能不是最短的方法,但很容易理解)--使用time.strptime()使用3种不同的格式通过尝试和错误加载时间字符串:
import time
from datetime import timedelta
def get_seconds(item):
try:
x = time.strptime(item, '%H hrs %M min %S sec')
except ValueError:
try:
x = time.strptime(item, '%M min %S sec')
except ValueError:
x = time.strptime(item, '%S sec')
return timedelta(hours=x.tm_hour, minutes=x.tm_min, seconds=x.tm_sec).total_seconds()
l = [
"2 hrs 5 min 15 sec",
"8 min 4 sec",
"2 sec"
]
for item in l:
print(get_seconds(item))打印每次字符串的总秒数:
7515.0
484.0
2.0发布于 2016-05-27 04:04:04
职能:
def hms_to_mins(t):
h, m, s = [int(i) for i in t.split(' ')]
return float(60*h + m + (s/60))
hms_to_mins('5 30 0')输出:330.0
您可以添加更多的东西来验证输入&检查是否有3个输入(hrs、mins和secs)。
如果要将输入设为“5hrs30mins2秒”并运行,请在上面的代码中使用以下内容(而不是hms_to_mins('5 30 0')):
import re
t=' '.join(re.findall('\d+', s))
hms_to_mins(t),所以代码是:
import re
def hms_to_mins(t):
h, m, s = [int(i) for i in t.split(' ')]
return float(60*h + m + (s/60))
s='5hrs3mins0sec' //your time string
t=(re.findall('\d+', s))
while(len(t)<3): t.append(str(0))
t=' '.join(t)
hms_to_mins(t)输出:303.0
发布于 2016-05-27 04:34:16
def str2dig(s):
nline = s.split(' ')
if len(nline) == 6:
minutes = int(nline[0])*60+int(nline[2])+ float(nline[4])/60
elif len(nline) == 4:
minutes = int(nline[0]) + float(nline[2])/60
else:
minutes = float(nline[0])/60
return round(minutes,2)
s = '2 hrs 5 min 15 sec'
print str2dig(s)
s = '8 min 4 sec'
print str2dig(s)
ll = ['2 hrs 5 min 15 sec', '8 min 4 sec']
newtime = [ str2dig(s) for s in ll ]
print newtime
#[125.25, 8.07]https://stackoverflow.com/questions/37474558
复制相似问题