Rounding up to nearest 30 minutes in python

Solution 1:

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

Solution 2:

to round forward you can use :

#!/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)))

To round back to the nearest 30th minute

def rounded_to_the_last_30th_minute_epoch():
    now = datetime.now()
    rounded = now - (now - datetime.min) % timedelta(minutes=30)
    return rounded