Python 中的舍入时间
在 Python 中对时间相关类型执行 ah/m/s 舍入操作并控制舍入分辨率的优雅、高效和 Pythonic 方法是什么?
我的猜测是,这需要时间模运算。说明性示例:
- 20:11:13%(10秒)=> (3秒)
- 20:11:13%(10分钟)==> (1分13秒)
我能想到的相关时间相关类型:
datetime.datetime
\datetime.time
struct_time
What would be an elegant, efficient and Pythonic way to perform a h/m/s rounding operation on time related types in Python with control over the rounding resolution?
My guess is that it would require a time modulo operation. Illustrative examples:
- 20:11:13 % (10 seconds) => (3 seconds)
- 20:11:13 % (10 minutes) => (1 minutes and 13 seconds)
Relevant time related types I can think of:
datetime.datetime
\datetime.time
struct_time
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
怎么样使用
datetime.timedelta
s:How about use
datetime.timedelta
s:对于 datetime.datetime 舍入,请参阅此函数:
https://stackoverflow.com/a/10854034/1431079
使用示例:
For a datetime.datetime rounding, see this function:
https://stackoverflow.com/a/10854034/1431079
Sample of use:
这会将时间数据四舍五入为问题中所要求的分辨率:
This will round up time data to a resolution as asked in the question:
您可以将两个时间都转换为秒,进行模运算
输出:
You can convert both times to seconds, do the modulo operati
Outputs:
我使用以下代码片段四舍五入到下一小时:
I use following code snippet to round to the next hour:
我想我会以秒为单位转换时间,并从那时起使用标准模运算。
20:11:13 =
20*3600 + 11*60 + 13
= 72673 秒72673 % 10 = 3
72673 % (10*60) = 73< /code>
这是我能想到的最简单的解决方案。
I think I'd convert the time in seconds, and use standard modulo operation from that point.
20:11:13 =
20*3600 + 11*60 + 13
= 72673 seconds72673 % 10 = 3
72673 % (10*60) = 73
This is the easiest solution I can think about.
这是每小时舍入的有损*版本:
相同的原理可以应用于不同的时间跨度。
*上述方法假设使用 UTC,因为任何时区信息在转换为时间戳时都会被破坏。
Here is a lossy* version of hourly rounding:
Same principle can be applied to different time spans.
*The above method assumes UTC is used, as any timezone information will be destroyed in conversion to timestamp.
非常丑陋,但如果只是一次性使用,则避免定义函数。
Very ugly, but avoids defining a function if the usage is just a one-off.
您还可以尝试 pandas.Timestamp.round:
如果要将结果更改回日期时间格式,可以执行以下操作:
You could also try pandas.Timestamp.round:
You can perform the following if you want to change the result back to datetime format: