在python中四舍五入到最接近的30分钟 [英] Rounding up to nearest 30 minutes in python
问题描述
我有以下代码.
我想将时间四舍五入到一小时内最接近的 30 分钟.例如:12:00PM 或 12:30PM 等等.
I would like to roundup TIME to the nearest 30 minutes in the hour. For example: 12:00PM or 12:30PM and so on.
EASTERN_NOW = timezone.localtime(timezone.now() + timedelta(minutes=30))
TIME = datetime.time(EASTERN_NOW.time().hour, EASTERN_NOW.time().minute).strftime(
VALID_TIME_FORMATS[2])
提前致谢
推荐答案
向上四舍五入到最接近的 30 分钟:
To round up to the nearest 30 minutes:
#!/usr/bin/env python3
from datetime import datetime, timedelta
def ceil_dt(dt, delta):
return dt + (datetime.min - dt) % delta
now = datetime.now()
print(now)
print(ceil_dt(now, timedelta(minutes=30)))
建议的公式是@Mark Dickinson(针对不同的问题).
2015-09-22 19:08:34.839915
2015-09-22 19:30:00
注意:如果输入是时区感知日期时间对象,例如 EASTERN_NOW
在你的情况下,那么你应该调用 timezone.make_aware(rounded_dt.replace(tzinfo=None))
如果您想保留舍入的本地时间并附加正确的 tzinfo,否则如果舍入跨越 DST 边界,您可能会得到错误的时区信息.或者为了避免在不明确的本地时间时失败,手动调用 .localize()
:
Note: if the input is timezone-aware datetime object such as EASTERN_NOW
in your case then you should call timezone.make_aware(rounded_dt.replace(tzinfo=None))
if you want to preserve the rounded local time and to attach the correct tzinfo, otherwise you may get wrong timezone info if the rounding crosses DST boundaries. Or to avoid failing for ambiguous local time, call .localize()
manually:
localize = getattr(rounded_dt.tzinfo, 'localize', None)
if localize:
rounded_dt = localize(rounded_dt.replace(tzinfo=None),
is_dst=bool(rounded_dt.dst()))
这篇关于在python中四舍五入到最接近的30分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!