Skip to content

Instantly share code, notes, and snippets.

@joedougherty
Created April 5, 2019 02:47
Show Gist options
  • Save joedougherty/9958ca2a97d56d4643a59b72215364cb to your computer and use it in GitHub Desktop.
Save joedougherty/9958ca2a97d56d4643a59b72215364cb to your computer and use it in GitHub Desktop.
find free time where you can
from datetime import date, datetime, time
class Block:
"""
Base class to represent a block of time.
Instantiation can be like:
# Use datetime objects directly
Block(datetime(2019,4,2,10,14,55), datetime(2019,4,2,12,15,30))
# If you just want times and don't need accurate dates
# (i.e. your time blocks won't span midnight)
# Hours are in the 0-23 range.
Block('10:35', '12:12')
"""
def __init__(self, start_time, end_time):
if isinstance(start_time, str):
hour, minute = start_time.split(':')
self.start_time = datetime.combine(date.min, time(int(hour), int(minute)))
elif isinstance(start_time, datetime):
self.start_time = start_time
else:
raise Exception
if isinstance(end_time, str):
hour, minute = end_time.split(':')
self.end_time = datetime.combine(date.min, time(int(hour), int(minute)))
elif isinstance(end_time, datetime):
self.end_time = end_time
else:
raise Exception
self.duration = self.end_time-self.start_time
def __repr__(self):
return 'start: {} | end: {} | dur: {}'.format(self.start_time, self.end_time, self.duration)
class BusyBlock(Block):
pass
class FreeBlock(Block):
pass
def process_blocks(blocks):
assert len(blocks) > 1
blocks = sorted(blocks, key=lambda b:b.start_time)
free_blocks = []
for idx, block in enumerate(blocks[0:-1]):
next_block = blocks[idx+1]
if next_block.start_time > block.end_time:
free_blocks.append(FreeBlock(block.end_time, next_block.start_time))
return free_blocks
test_blocks = [
BusyBlock('00:37', '12:34'),
BusyBlock('12:34', '23:59'),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment