Created
November 1, 2018 20:59
-
-
Save cupdike/c5554233e1dd6b233a9b6ec6adb05c5a to your computer and use it in GitHub Desktop.
Python function to round down minutes to a user specified resolution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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