如何舍入日期时间对象的分钟 [英] How to round the minute of a datetime object

查看:68
本文介绍了如何舍入日期时间对象的分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 datetime 对象,该对象使用 strptime()生成。

I have a datetime object produced using strptime().

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

我需要将分钟数舍入到最接近的第10分钟。到目前为止,我一直在做分钟值,并在其上使用round()。

What I need to do is round the minute to the closest 10th minute. What I have been doing up to this point was taking the minute value and using round() on it.

min = round(tm.minute, -1)

但是,与上面的示例一样,当分钟值大于56时,它将给出无效的时间。即:3:60

However, as with the above example, it gives an invalid time when the minute value is greater than 56. i.e.: 3:60

有什么更好的方法? datetime 是否支持此功能?

What is a better way to do this? Does datetime support this?

推荐答案

这将获得 floor将存储在tm中的 datetime 对象的值四舍五入到 tm 之前的10分钟。

This will get the 'floor' of a datetime object stored in tm rounded to the 10 minute mark before tm.

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

如果您想将经典舍入到最近的10分钟标记,请执行以下操作:

If you want classic rounding to the nearest 10 minute mark, do this:

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)

这篇关于如何舍入日期时间对象的分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆