[英]How to convert elapsed time string to seconds in Python
有谁知道是否有一个“简单”功能可以将以下经过的时间字符串转换为秒? 2d1h39m53s
取决于经过了多少时间,并非所有字段都将出现。
我已经看过strptime和datetime,但是如果不为此编写自己的函数,似乎没有什么比这更合适的了。 只是想节省时间。 谢谢
我将它写到几天前就清楚地验证了运行时。 在下面的两个定义之后,只需在要计数的代码起点处写“ tic()”,在终点处写“ toc()”,即可为您提供清晰的时间数据读取。 希望能帮助到你。
import time
import math
def tic():
global startTime_for_tictoc
startTime_for_tictoc = time.time()
def toc():
if 'startTime_for_tictoc' in globals():
tf = time.time() - startTime_for_tictoc;
if tf < 60:
print("\nElapsed time: %f seconds.\n" % tf)
elif 60 < tf < 3600:
mm = math.floor(tf/60)
ss = tf - (60*mm)
print("\nElapsed time: %d minute(s) and %f seconds.\n" % (mm, ss))
elif 3600 < tf < 86400:
hh = math.floor(tf/3600)
mm = math.floor((tf-(hh*3600))/60)
ss = tf - (hh*3600) - (60*mm)
print("\nElapsed time: %d hour(s) %d minute(s) and %f seconds.\n" % (hh, mm, ss))
elif tf > 86400:
dd = math.floor(tf/86400)
hh = math.floor((tf-(dd*86400))/3600)
mm = math.floor((tf-(dd*86400)-(hh*3600))/60)
ss = tf - (86400*dd) - (hh*3600) - (60*mm)
print("\nElapsed time: %d day(s) %d hour(s) %d minute(s) and %f seconds.\n" % (dd, hh, mm, ss))
else:
print("\nToc: start time not set")
不知道那里是否有功能,但这可以完成工作。 同样适用于“ 2d1h53s”之类的值。
d = []
h = []
m = []
s = []
sd = 0
sh = 0
sm = 0
ss = 0
str = "2d1h39m53s"
i = 0
if str.find("d") > 0:
i = str.find("d")
d.append(str[0:i])
str = str[i:]
if str.find("h") > 0:
i = str.find("h")
h.append(str[1:i])
str = str[i:]
if str.find("m") > 0:
i = str.find("m")
m.append(str[1:i])
str = str[i:]
if str.find("s") > 0:
i = str.find("s")
s.append(str[1:i])
str = str[i:]
try:
sd = float(d[0]) * 24 * 60 * 60
except:
sd = 0
try:
sh = float(h[0]) * 60 * 60
except:
sh = 0
try:
sm = float(m[0]) * 60
except:
sm = 0
try:
ss = float(s[0])
except:
ss = 0
print("seconds")
sec = sd + sh + sm + ss
print(sec)
如果您的日期时间具有给定的格式,则可以执行以下操作:
import re
import numpy as np
from functools import reduce
split_strings = ['D', 'h','m','s']
def datestring_to_seconds(datestring):
values_and_units = [(int(string[:-1]), string[-1]) for string in [re.search(f"([0-9]+){split_string}",
f"{datestring}".replace('d', 'D')).group(0) for split_string in split_strings]]
return reduce(lambda x,y : x+y, [np.timedelta64(*x) for x in values_and_units])/np.timedelta64(1, 's')
结果
datestring_to_seconds("2d1h39m53s")
178793.0
一些解释:首先在字符串中搜索任何一个,最多匹配一个split_strings
(例如39m
)前面的两位,然后将其转换为元组(39, "m")
。 我们对split_strings
每个字符串执行此操作,并将结果保存在列表values_and_units
,在我们的特殊情况下,看起来像这样:
[(2, 'D'), (1, 'h'), (39, 'm'), (53, 's')]
现在,这些元素的每个元素都可以强制转换为numpy timedelta64。 reduce操作将所有时间增量相加,然后除以np.timedelta64(1, 's')
得到具有所需秒数的浮点数。
这是一个纯python解决方案。
import re
s = '2d1h39m53s'
d = {'d':86400,'h':3600, 'm':60, 's':1}
secs = 0
m = re.match(r'(\d+)([dhms])', s)
while m is not None:
secs += int(m.group(1)) * d[m.group(2)]
s = re.sub(r'\d+[dhms]', '', s, 1)
m = re.match(r'(\d+)([dhms])', s)
print(secs)
print(secs)
印刷:178793
编辑:使用match.end()定位下一个搜索的开始。 不会破坏字符串s和更干净的解决方案。
import re
s = '2d1h39m53s'
d = {'d':86400,'h':3600, 'm':60, 's':1}
secs = 0
pat = re.compile('(\d+)([dhms])')
m = pat.search(s)
while m is not None:
pos = m.end()
secs += int(m.group(1)) * d[m.group(2)]
m = pat.search(s, pos)
print(secs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.