Skip to content

Instantly share code, notes, and snippets.

@danielthiel
Created April 6, 2015 12:22
Show Gist options
  • Save danielthiel/45fa7a5133f6026f6ef8 to your computer and use it in GitHub Desktop.
Save danielthiel/45fa7a5133f6026f6ef8 to your computer and use it in GitHub Desktop.
Round up the minutes of a datetime object to any minute factor
import datetime
import math
def round_up_minutes(dt=None, minute_factor=60):
""" Round up the minutes of a datetime object to any minute factor
dt : datetime.datetime object, default now.
minute_factor : number to which closest factor the minutes will round up
with minute_factor = 15 it would round up to the closest quarter hour (0, 15, 30, 45)
with minute_factor = 60 it would always round up to the next full hour
"""
if dt is None:
dt = datetime.datetime.now()
upmins = math.ceil(float(dt.minute)/minute_factor)*minute_factor
diffmins = upmins - dt.minute
newtime = dt + datetime.timedelta(minutes=diffmins)
newtime = newtime.replace(second=0)
newtime = newtime.replace(microsecond=0)
return newtime
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment