如何对datetime对象的分钟进行舍入

133 投票
22 回答
198686 浏览
提问于 2025-04-16 02:40

我有一个通过 strptime() 生成的 datetime 对象。

>>> tm
datetime.datetime(2010, 6, 10, 3, 56, 23)

我想做的是把分钟数四舍五入到最接近的10分钟。到目前为止,我一直是取分钟的数值,然后用 round() 函数来处理。

min = round(tm.minute, -1)

但是,像上面的例子那样,当分钟数大于56时,它会给出一个无效的时间,比如:3:60。

有没有更好的方法来做到这一点?datetime 支持这样做吗?

22 个回答

21

我根据最佳答案进行了修改,做了一个只使用日期时间对象的版本,这样就不需要把时间转换成秒了,调用的代码也变得更容易理解:

def roundTime(dt=None, dateDelta=datetime.timedelta(minutes=1)):
    """Round a datetime object to a multiple of a timedelta
    dt : datetime.datetime object, default now.
    dateDelta : timedelta object, we round to a multiple of this, default 1 minute.
    Author: Thierry Husson 2012 - Use it as you want but don't blame me.
            Stijn Nevens 2014 - Changed to use only datetime objects as variables
    """
    roundTo = dateDelta.total_seconds()

    if dt == None : dt = datetime.datetime.now()
    seconds = (dt - dt.min).seconds
    # // is a floor division, not a comment on following line:
    rounding = (seconds+roundTo/2) // roundTo * roundTo
    return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)

这里有一些示例,分别是1小时和15分钟的四舍五入:

print roundTime(datetime.datetime(2012,12,31,23,44,59),datetime.timedelta(hour=1))
2013-01-01 00:00:00

print roundTime(datetime.datetime(2012,12,31,23,44,49),datetime.timedelta(minutes=15))
2012-12-31 23:30:00
116

这是一个通用的函数,可以把日期时间按照任意秒数的间隔进行四舍五入:

def roundTime(dt=None, roundTo=60):
   """Round a datetime object to any time lapse in seconds
   dt : datetime.datetime object, default now.
   roundTo : Closest number of seconds to round to, default 1 minute.
   Author: Thierry Husson 2012 - Use it as you want but don't blame me.
   """
   if dt == None : dt = datetime.datetime.now()
   seconds = (dt.replace(tzinfo=None) - dt.min).seconds
   rounding = (seconds+roundTo/2) // roundTo * roundTo
   return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)

下面是一些例子,展示了如何把时间四舍五入到1小时和30分钟:

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
2013-01-01 00:00:00

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=30*60)
2012-12-31 23:30:00
169

这段代码会把一个存储在变量 tm 中的 datetime 对象向下取整,调整到离 tm 最近的10分钟的整点。

tm = tm - datetime.timedelta(minutes=tm.minute % 10,
                             seconds=tm.second,
                             microseconds=tm.microsecond)

如果你想要经典的四舍五入到最近的10分钟整点,可以这样做:

discard = datetime.timedelta(minutes=tm.minute % 10,
                             seconds=tm.second,
                             microseconds=tm.microsecond)
tm -= discard
if discard >= datetime.timedelta(minutes=5):
    tm += datetime.timedelta(minutes=10)

或者这样:

tm += datetime.timedelta(minutes=5)
tm -= datetime.timedelta(minutes=tm.minute % 10,
                         seconds=tm.second,
                         microseconds=tm.microsecond)

撰写回答