在Python中累加时间持续时间
我想在Python中把一系列的时间分段加起来。这些时间最开始是像“00:08:30.291”这样的字符串。我找不到合适的方法来使用Python的对象或API,让这个过程变得方便和优雅。看起来时间对象不支持微秒,所以我用datetime的strptime来解析这些字符串,成功了。但是,datetime对象似乎不能直接相加,我其实不想让时间溢出到天数(比如说23小时加2小时等于25小时)。我可以使用datetime.time,但它们也不能相加。timedelta看起来是合适的,但从其他格式转换过来又有点麻烦。也许我在这里漏掉了什么明显的东西。我希望能够:
for timestring in times:
t = datetime.strptime("%H:%M:%S.%f", timestring).time
total_duration = total_duration + t
print total_duration.strftime("%H:%M:%S.%f")
2 个回答
0
import numpy as np
# read file with one duration per line
with open('clean_times.txt', 'r') as f:
x = f.read()
# Convert string to list of '00:02:12.31'
# I had to drop last item (empty string)
tmp = x.split('\n')[:-1]
# get list of ['00', 02, '12.31']
tmp = [i.split(':') for i in tmp.copy()]
# create numpy array with floats
np_tmp = np.array(tmp, dtype=np.float)
# sum via columns and divide
# hours/24 minutes/60 milliseconds/1000
# X will be a float array [days, hours, seconds]
# Something like `array([ 0. , 15.68333333, 7.4189 ])`
X = np_tmp.sum(axis=0) / np.array([24, 60, 1000])
我在这里很开心,但如果你需要像 '15:41:07.518'
这样的复杂字符串作为输出,那就继续往下看吧。
# X will be a float array [hours, hours, seconds]
X = np_tmp.sum(axis=0) / np.array([1, 60, 1000])
# ugly part
# Hours are integer parts
H = int(X[0]) + int(X[1])
# Minutes are hour fractional part and integer minutes part
tmp_M = (X[0] % 1 + X[1] % 1) * 60
M = int(tmp_M)
# Seconds are minutes fractional part and integer seconds part
tmp_S = tmp_M % 1 * 60 + X[2]
S = int(tmp_S)
# Milliseconds are seconds fractional part
MS = int(tmp_S % 1 * 1000)
# merge string for output
# Something like '15:41:07.518'
result = f'{H:02}:{M:02}:{S:02}.{MS:03}'
13
你正在处理的是时间差,所以在这里使用 datetime.timedelta
是合适的选择:
>>> import datetime
>>> d1 = datetime.datetime.strptime("00:08:30.291", "%H:%M:%S.%f")
>>> d1
datetime.datetime(1900, 1, 1, 0, 8, 30, 291000)
>>> d2
datetime.datetime(1900, 1, 1, 0, 2, 30, 291000)
>>> dt1 = datetime.timedelta(minutes=d1.minute, seconds=d1.second, microseconds=d1.microsecond)
>>> dt2 = datetime.timedelta(minutes=d2.minute, seconds=d2.second, microseconds=d2.microsecond)
>>> fin = dt1 + dt2
>>> fin
datetime.timedelta(0, 660, 582000)
>>> str(fin)
'0:11:00.582000'
另外,请不要给你的变量起像 sum
这样的名字,这样会覆盖掉内置的功能。