Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
round a datetime to minutes
import datetime
def floor_to_minute(time, minutes):
time = time - datetime.timedelta(
minutes=time.minute % minutes,
seconds=time.second,
microseconds=time.microsecond)
return time
def ceil_to_minute(time, minutes):
time += datetime.timedelta(minutes=minutes)
time = floor_to_minute(time, minutes)
return time
def minute_interval(starttime, endtime, step_width, include_start=False):
time = starttime
rounding_func = floor_to_minute if include_start else ceil_to_minute
time = rounding_func(time, step_width)
steps = [time]
while True:
time += datetime.timedelta(minutes=step_width)
if time > endtime:
return steps
steps.append(time)
if __name__ == '__main__':
from pprint import pprint
starttime = datetime.datetime(2014, 9, 18, 8, 5, 0)
endtime = starttime + datetime.timedelta(hours=3.5)
print(starttime, floor_to_minute(starttime, 15))
print(starttime, ceil_to_minute(starttime, 15))
print(starttime, endtime)
pprint(minute_interval(starttime, endtime, 15, True))
@vindolin

This comment has been minimized.

Copy link
Owner Author

@vindolin vindolin commented Sep 18, 2014

$ python round_to_minutes.py

(datetime.datetime(2014, 9, 18, 8, 5), datetime.datetime(2014, 9, 18, 8, 0))
(datetime.datetime(2014, 9, 18, 8, 5), datetime.datetime(2014, 9, 18, 8, 15))
(datetime.datetime(2014, 9, 18, 8, 5), datetime.datetime(2014, 9, 18, 11, 35))
[datetime.datetime(2014, 9, 18, 8, 0),
 datetime.datetime(2014, 9, 18, 8, 15),
 datetime.datetime(2014, 9, 18, 8, 30),
 datetime.datetime(2014, 9, 18, 8, 45),
 datetime.datetime(2014, 9, 18, 9, 0),
 datetime.datetime(2014, 9, 18, 9, 15),
 datetime.datetime(2014, 9, 18, 9, 30),
 datetime.datetime(2014, 9, 18, 9, 45),
 datetime.datetime(2014, 9, 18, 10, 0),
 datetime.datetime(2014, 9, 18, 10, 15),
 datetime.datetime(2014, 9, 18, 10, 30),
 datetime.datetime(2014, 9, 18, 10, 45),
 datetime.datetime(2014, 9, 18, 11, 0),
 datetime.datetime(2014, 9, 18, 11, 15),
 datetime.datetime(2014, 9, 18, 11, 30)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.