如何以±5秒的精度取整时间?
from datetime import datetime
times = ['00:00:12.00', '00:00:12.5', '00:00:18.00', '00:00:58.00', '23:59:57.51']
for time in times:
obj = datetime.strptime(time, '%H:%M:%S.%f')
rounded = obj # todo round it with +-5 sec precision (how?)
print datetime.strftime(rounded, '%H:%M:%S') + ',',
# should print:
# 00:00:10, 00:00:15, 00:00:20, 00:01:00, 00:00:00,
from datetime import datetime
from datetime import timedelta
times = ['00:00:12.00', '00:00:12.5', '00:00:18.00', '00:00:58.00',
'23:59:57.51', '03:59:52.49999']
def round_seconds(dt, precision):
# Max value for microseconds in `datetime` is 999999 (6 digits).
# We need to pad the free space with zeros if `dt.microsecond`
# has less than 6 digits
msfloat = '0.{0}{1}'.format(''.zfill(6 - len(str(dt.microsecond))),
dt.microsecond)
mod = dt.second % precision + float(msfloat)
diff = precision - mod
if diff == mod:
# Ambiguous (xxxxxxx.5), gotta ceil it
delta = mod
else:
# Choose the closest bound
delta = min(diff, mod)
if delta == mod:
# Negate if need to floor it
delta = -mod
return dt + timedelta(seconds=delta)
for time in times:
obj = datetime.strptime(time, '%H:%M:%S.%f')
print datetime.strftime(round_seconds(obj, 5), '%H:%M:%S')+',',
输出:
00:00:10, 00:00:15, 00:00:20, 00:01:00, 00:00:00, 03:59:50,
这样的东西应该可以工作:
from datetime import timedelta
....
obj = datetime.strptime(time, '%H:%M:%S.%f')
offset = obj.seconds % 5
if offset < 3:
rounded = obj + timedelta(seconds=obj.seconds-offset)
else:
rounded = obj + timedelta(seconds=obj.seconds+(5-offset))