Skip to content

Instantly share code, notes, and snippets.

@cupdike
Created November 1, 2018 20:59
Show Gist options
  • Save cupdike/c5554233e1dd6b233a9b6ec6adb05c5a to your computer and use it in GitHub Desktop.
Save cupdike/c5554233e1dd6b233a9b6ec6adb05c5a to your computer and use it in GitHub Desktop.
Python function to round down minutes to a user specified resolution
from datetime import datetime, timedelta
def round_minutes(dt, resolutionInMinutes):
"""round_minutes(datetime, resolutionInMinutes) => datetime rounded to lower interval
Works for minute resolution up to a day (e.g. cannot round to nearest week).
"""
# First zero out seconds and micros
dtTrunc = dt.replace(second=0, microsecond=0)
# Figure out how many minutes we are past the last interval
excessMinutes = (dtTrunc.hour*60 + dtTrunc.minute) % resolutionInMinutes
# Subtract off the excess minutes to get the last interval
return dtTrunc + timedelta(minutes=-excessMinutes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment