如何舍入日期时间对象的分钟

编程入门 行业动态 更新时间:2024-10-24 01:56:05
本文介绍了如何舍入日期时间对象的分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 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)

更多推荐

如何舍入日期时间对象的分钟

本文发布于:2023-10-16 05:31:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496643.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   日期   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!