圆形日期时间对象数据,精度为±5秒

时间:2014-04-30 03:50:33

标签: python datetime

如何以±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,

2 个答案:

答案 0 :(得分:1)

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,

答案 1 :(得分:0)

这样的事情应该有效:

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))
相关问题