Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

time - Rounding up to nearest 30 minutes in python

I have the following code below.

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])

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)))

The formula is suggested by @Mark Dickinson (for a different question).

Output

2015-09-22 19:08:34.839915
2015-09-22 19:30:00

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()))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...