我有一个 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)更多推荐
如何舍入日期时间对象的分钟
发布评论