Skip to content

Instantly share code, notes, and snippets.

@lucndm
Created March 24, 2016 09:23
Show Gist options
  • Save lucndm/198d96b14cdbf397a808 to your computer and use it in GitHub Desktop.
Save lucndm/198d96b14cdbf397a808 to your computer and use it in GitHub Desktop.
Round Time With Python
# https://stackoverflow.com/questions/3463930/how-to-round-the-minute-of-a-datetime-object-python/10854034#10854034
def roundTime(dt=None, roundTo=60):
"""Round a datetime object to any time laps in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
"""
if dt == None : dt = datetime.datetime.now()
seconds = (dt - dt.min).seconds
# // is a floor division, not a comment on following line:
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment