且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在python中四舍五入到最接近的30分钟

更新时间:2023-08-29 12:39:46

向上四舍五入到最接近的 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()))