在python中查找当前时间间隔?

发布于 2024-10-18 11:51:35 字数 280 浏览 6 评论 0原文

如何在 python 中找到最近的 15(或 10)分钟间隔? 例如,

>>> datetime.datetime.now()
datetime.datetime(2011, 2, 22, 15, 43, 18, 424873)

我想要当前 15 分钟间隔(15:30-15:44),所以我想将上面的日期时间转换为

datetime.datetime(2011, 2, 22, 15, 30, 00, 00)

How can I find the nearest 15 (or 10) minute interval in python ?
e.g.

>>> datetime.datetime.now()
datetime.datetime(2011, 2, 22, 15, 43, 18, 424873)

I'd like the current 15 minute interval (15:30-15:44) so I'd like to transform the above datetime to a

datetime.datetime(2011, 2, 22, 15, 30, 00, 00)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

诺曦 2024-10-25 11:51:35

对我来说最简单的方法:

from datetime import datetime, timedelta
now = datetime.now()
now = now - timedelta(minutes = now.minute % 15, seconds = now.second, microseconds = now.microsecond )

希望有帮助。

Quite the easiest way to me:

from datetime import datetime, timedelta
now = datetime.now()
now = now - timedelta(minutes = now.minute % 15, seconds = now.second, microseconds = now.microsecond )

Hope that'll help.

梦里人 2024-10-25 11:51:35

我认为对于这种情况,使用 replacetimedelta

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.replace(minute=(now.minute - (now.minute % 15)), second=0, microsecond=0)
datetime.datetime(2012, 3, 23, 11, 15)
>>> 

I think for this case using replace is more straightforward than timedelta:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.replace(minute=(now.minute - (now.minute % 15)), second=0, microsecond=0)
datetime.datetime(2012, 3, 23, 11, 15)
>>> 
小梨窩很甜 2024-10-25 11:51:35

只需将分钟设置为

min = min - min %  15 

0,并将较短的时间单位(秒、毫秒、..)设置为 0

Just set minutes on

min = min - min %  15 

and set shorter time units (seconds, msec, ..) on 0

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文