Created
April 4, 2016 21:05
-
-
Save jesperp/222c7bf7a32df689af43d15d5ee5790b to your computer and use it in GitHub Desktop.
Generate office hours
This file contains hidden or 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
import itertools | |
from datetime import time, timedelta, datetime | |
OFFICE_OPEN = time(8, 0, 0) | |
OFFICE_CLOSE = time(16, 0, 0) | |
def isofficehour(dt): | |
t = dt.time() | |
if dt.weekday() in (5,6): # Weekend | |
return False | |
return OFFICE_OPEN <= t and t <= OFFICE_CLOSE | |
def datetimes(starting): | |
for i in itertools.count(): | |
t = starting.time() | |
if (i == 0 and t < OFFICE_OPEN) or i != 0: | |
t = OFFICE_OPEN | |
yield starting.replace(hour=t.hour, minute=t.minute, second=t.second) + timedelta(days=i) | |
def officehours(starting=None): | |
if starting is None: | |
starting = datetime.now() | |
return itertools.ifilter(isofficehour, datetimes(starting)) | |
def test(): | |
""" | |
If the starting time is within office hour, pick the same day | |
>>> from datetime import datetime | |
>>> officehours(starting=datetime(2016, 4, 4, 13, 45, 20)).next() | |
datetime.datetime(2016, 4, 4, 13, 45, 20) | |
If the starting time is after office hours, pick the next day | |
>>> officehours(starting=datetime(2016, 4, 4, 6, 30)).next() | |
datetime.datetime(2016, 4, 4, 8, 0) | |
If the starting time is before office hours, pick the same day | |
>>> officehours(starting=datetime(2016, 4, 4, 16, 0, 1)).next() | |
datetime.datetime(2016, 4, 5, 8, 0) | |
Let's step through an officehour generator, starting with friday | |
>>> someday = datetime(2016, 4, 8, 6, 36) | |
>>> someday.strftime("%A"), someday.time().isoformat() | |
('Friday', '06:36:00') | |
Friday morning is before office hours so the next() will pick same day | |
>>> gen = officehours(starting=someday) | |
>>> dt = gen.next() | |
>>> dt.strftime("%A"), dt.time().isoformat() | |
('Friday', '08:00:00') | |
The next officehour will be monday because weekends are closed | |
>>> dt = gen.next() | |
>>> dt.strftime("%A"), dt.time().isoformat() | |
('Monday', '08:00:00') | |
Next will be tuesday, because tuesday is nothing special | |
>>> dt = gen.next() | |
>>> dt.strftime("%A"), dt.time().isoformat() | |
('Tuesday', '08:00:00') | |
""" | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment