如何舍入日期时间对象的分钟
我有一个使用 strptime()
生成的 datetime
对象。
>>> tm
datetime.datetime(2010, 6, 10, 3, 56, 23)
我需要做的是将分钟四舍五入到最接近的第 10 分钟。到目前为止我一直在做的是获取分钟值并对其使用 round() 。
min = round(tm.minute, -1)
但是,与上面的示例一样,当分钟值大于 56 时,它会给出无效时间。即:3:60
有什么更好的方法来执行此操作? datetime
支持这个吗?
I have a datetime
object produced using strptime()
.
>>> tm
datetime.datetime(2010, 6, 10, 3, 56, 23)
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)
However, as with the above example, it gives an invalid time when the minute value is greater than 56. i.e.: 3:60
What is a better way to do this? Does datetime
support this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
这将使存储在 tm 中的
datetime
对象的“下限”四舍五入到tm
之前的 10 分钟标记。如果您想要经典四舍五入到最接近的 10 分钟标记,请执行以下操作:
或执行以下操作:
This will get the 'floor' of a
datetime
object stored in tm rounded to the 10 minute mark beforetm
.If you want classic rounding to the nearest 10 minute mark, do this:
or this:
在任何时间(以秒为单位)舍入日期时间的一般函数:
具有 1 小时舍入和 1 小时舍入的示例30分钟四舍五入:
General function to round a datetime at any time lapse in seconds:
Samples with 1 hour rounding & 30 minutes rounding:
从我修改为仅使用日期时间对象的改编版本,这避免了必须转换为秒并使调用代码更具可读性:
具有 1 小时舍入和 1 小时舍入的示例15分钟四舍五入:
From the best answer I modified to an adapted version using only datetime objects, this avoids having to do the conversion to seconds and makes the calling code more readable:
Samples with 1 hour rounding & 15 minutes rounding:
我使用了 Stijn Nevens 代码(谢谢 Stijn),并且有一些附加组件可以分享。向上舍入、向下舍入以及四舍五入到最接近的值。
更新 2019-03-09 = 纳入 Spinxz 评论;谢谢。
更新 2019-12-27 = 纳入 Bart 评论;谢谢。
测试 date_delta 为“X 小时”或“X 分钟”或“X 秒”。
I used Stijn Nevens code (thank you Stijn) and have a little add-on to share. Rounding up, down and rounding to nearest.
update 2019-03-09 = comment Spinxz incorporated; thank you.
update 2019-12-27 = comment Bart incorporated; thank you.
Tested for date_delta of "X hours" or "X minutes" or "X seconds".
这是一个更简单的通用解决方案,没有浮点精度问题和外部库依赖性:
在您的情况下:
Here is a simpler generalized solution without floating point precision issues and external library dependencies:
In your case:
Pandas 具有日期时间循环功能,但与 Pandas 中的大多数内容一样,它需要采用系列格式。
文档 - 更改频率根据需要字符串。
Pandas has a datetime round feature, but as with most things in Pandas it needs to be in Series format.
Docs - Change the frequency string as needed.
如果你不想使用条件,你可以使用
modulo
运算符:UPDATE
你想要这样的东西吗?
..如果你想要结果作为字符串。为了获得日期时间结果,最好使用 timedelta - 请参阅其他响应;)
if you don't want to use condition, you can use
modulo
operator:UPDATE
did you want something like this?
.. if you want result as string. for obtaining datetime result, it's better to use timedelta - see other responses ;)
我正在用这个。它的优点是可以使用 tz 感知的日期时间。
它的缺点是只能工作少于一小时的时间片。
i'm using this. it has the advantage of working with tz aware datetimes.
it has the disadvantage of only working for timeslices less than an hour.
一个简单的方法:
A straightforward approach:
对分钟时间进行舍入的一般函数:
General Function to round down times of minutes:
这样就可以了,我认为它使用了 round 的一个非常有用的应用程序。
结果:
This will do it, I think it uses a very useful application of round.
The result:
是的,如果您的数据属于 pandas 系列中的 DateTime 列,您可以使用内置的 pandas.Series.dt.round 函数对其进行舍入。
请参阅此处有关 pandas.Series 的文档。 dt.round。
在四舍五入到 10 分钟的情况下,它将是 Series.dt.round('10min') 或 Series.dt.round('600s') ,如下所示:
编辑以添加示例代码:
yes, if your data belongs to a DateTime column in a pandas series, you can round it up using the built-in pandas.Series.dt.round function.
See documentation here on pandas.Series.dt.round.
In your case of rounding to 10min it will be Series.dt.round('10min') or Series.dt.round('600s') like so:
Edit to add Example code:
我想出了这个非常简单的函数,可以处理任何时间增量,只要它是 60 秒的倍数或除数即可。它还与时区感知的日期时间兼容。
输出:
I came up with this very simple function, working with any timedelta as long as it's either a multiple or divider of 60 seconds. It's also compatible with timezone-aware datetimes.
Output:
这些看起来过于复杂
Those seem overly complex
基于 Stijn Nevens 并针对 Django 进行修改,用于将当前时间四舍五入到最接近的 15 分钟。
如果您需要完整的日期和时间,只需删除
.strftime('%H:%M:%S')
Based on Stijn Nevens and modified for Django use to round current time to the nearest 15 minute.
if you need full date and time just remove the
.strftime('%H:%M:%S')
当捕获异常时,速度不是最好的,但是这可以工作。
时间安排
Not the best for speed when the exception is caught, however this would work.
Timings
对于
datetime
对象t
,四舍五入到给定时间单位(这里是秒)的两行直观解决方案:如果您希望四舍五入到不同的单位,只需更改
格式_str
。这种方法不会像上面的方法那样舍入到任意时间量,而是一种很好的 Pythonic 方法,可以舍入到给定的小时、分钟或秒。
A two line intuitive solution to round to a given time unit, here seconds, for a
datetime
objectt
:If you wish to round to a different unit simply alter
format_str
.This approach does not round to arbitrary time amounts as above methods, but is a nicely Pythonic way to round to a given hour, minute or second.
其他解决方案:
希望这有帮助!
Other solution:
Hope this helps!
我知道的最短路线
The shortest way I know
对于这样一个简单的问题来说,大多数答案似乎都太复杂了。
假设
your_time
是您拥有的日期时间对象,接下来的轮次(实际上是楼层)以分钟为单位定义的所需分辨率。Most of the answers seem to be too complicated for such a simple question.
Assuming
your_time
is the datetime object your have, the following rounds (actually floors) it at a desired resolution defined in minutes.下面的函数只需最少的导入就可以完成这项工作。您可以通过设置参数unit、rnd 和frm 舍入到您想要的任何值。尝试一下这个函数,您就会发现它是多么容易。
调用函数如下:
使用默认输出格式 = hh:mm 舍入到最近的 5 分钟,如下
或使用输出格式 hh:mm:ss 舍入到最近的小时,如下
最后更新版本
The function below with minimum of import will do the job. You can round to anything you want by setting te parameters unit, rnd, and frm. Play with the function and you will see how easy it will be.
Call function as follow:
Round to nearest 5 minutes with default ouput format = hh:mm as follow
Or round to nearest hour with ouput format hh:mm:ss as follow
last updated version
MZA 提出的https://stackoverflow.com/a/32547090/4417769,但更简单。
我本来会保留
date_delta
,但同事将其修改为使用round_to
,所以这就是现在的样子。请随意提出修改以使用原始date_delta
参数。应该与时区一起工作,尚未彻底测试。
还没有实现
平均
,无论那是什么。无论如何,我们的代码中没有使用它。What MZA proposed https://stackoverflow.com/a/32547090/4417769, but way simpler.
I would have kept
date_delta
, but it was modified by colleagues to useround_to
, so this is what this is now. Feel free to propose an edit to use the originaldate_delta
parameter.Should work with timezones, haven't thoroughly tested that yet.
haven't implemented
average
, whatever that is. Wasn't in use in our code anyway.