Skip to content

Instantly share code, notes, and snippets.

@jayhale
Last active September 7, 2018 14:35
Show Gist options
  • Save jayhale/4a41e967285803327fc63cce92275a29 to your computer and use it in GitHub Desktop.
Save jayhale/4a41e967285803327fc63cce92275a29 to your computer and use it in GitHub Desktop.
Python time quantizer
"""
A simple time quantizer for python. Takes in a time and gives back the
quantized time given resolution in seconds. Always rounds down.
"""
from datetime import datetime
def quantize_time(time, resolution):
"""Round a time object to the previous time appropriate for resolution"""
if not time or not isinstance(time, datetime):
raise ValueError(
'time parameter is required and must be a datetime instance')
if not resolution or not isinstance(resolution, int) or resolution < 1:
raise ValueError('resolution parameter must be a supported resolution')
factors_60 = (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30)
# <1 minute
if resolution in factors_60:
quantized_second = int(floor(time.second/resolution)*resolution)
return time.replace(microsecond=0, second=quantized_second)
# <1 hour
if resolution in [60*x for x in factors_60]:
resolution = resolution/60
quantized_minute = int(floor(time.minute/resolution)*resolution)
return time.replace(microsecond=0, second=0, minute=quantized_minute)
# <1 day
if resolution in [60*60*x for x in (1, 2, 3, 4, 6, 8, 12)]:
resolution = resolution/(60*60)
quantized_hour = int(floor(time.hour/resolution)*resolution)
return time.replace(microsecond=0, second=0, minute=0,
hour=quantized_hour)
# 1 day
if resolution == 60*60*24:
return time.replace(microsecond=0, second=0, minute=0, hour=0)
# 1 week
if resolution == 60*60*24*7:
quantized_day = time.day - time.weekday() # Week starts on Monday
# If the quantized day is in the current month
if quantized_day > 0:
return time.replace(microsecond=0, second=0, minute=0, hour=0,
day=quantized_day)
# Otherwise, it must be in the previous month, and we should decrement
# month in the date
else:
month = time.month - 1
year = time.year
# If the quantized month is in the prevous year
if month < 1:
month = 12
year = time.year - 1
quantized_day = calendar.monthrange(year, month)[1] + quantized_day
return time.replace(microsecond=0, second=0, minute=0, hour=0,
day=quantized_day, month=month, year=year)
raise ValueError('Resolution not supported')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment