Skip to content

Instantly share code, notes, and snippets.

@Jeffallan
Created September 28, 2019 19:04
Show Gist options
  • Save Jeffallan/3439cfc138f8cccc071ba9db19e47790 to your computer and use it in GitHub Desktop.
Save Jeffallan/3439cfc138f8cccc071ba9db19e47790 to your computer and use it in GitHub Desktop.
easy time rounding for python
"""
function rounded_time
param: dt a date time object
kwarg: rnd the number of minutes to round to
Since datetime attributes are integers round them like a normal integer
This function will roll over hours i.e 10:59 -> 11:00
This function will roll over days i.e 23:59 01/01 -> 00:00 01/02
"""
from datetime imort datetime, timedelta
def rounded_time(dt, rnd=15):
return (
dt.replace(microsecond=0,
second=0,
minute=0,
hour=dt.hour) +
timedelta(minutes=int(round(dt.minute/rnd)*rnd))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment