Last active
August 6, 2019 13:13
-
-
Save md2perpe/cf1287ba84adf3b6d95269850db86040 to your computer and use it in GitHub Desktop.
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 datetime | |
FIRST_MONDAY = datetime.datetime(1970, 1, 5, tzinfo=datetime.timezone.utc).timestamp() | |
HOUR = 3600 | |
DAY = 24*HOUR | |
WEEK = 7*DAY | |
CLOSE_HOUR = 22 | |
OPEN_HOUR = 8 | |
OPEN_DAYS_PER_WEEK = 5 # Monday - Friday | |
OPEN_HOURS_PER_DAY = CLOSE_HOUR - OPEN_HOUR | |
OPEN_HOURS_PER_WEEK = OPEN_DAYS_PER_WEEK * OPEN_HOURS_PER_DAY | |
def primitive(ts): | |
""" | |
Counting open hours (8:00 -- 22:00, Monday -- Friday) since first Monday after beginning of unix epoch | |
""" | |
ts -= FIRST_MONDAY | |
whole_weeks = ts // WEEK | |
ts %= WEEK | |
whole_days = ts // DAY | |
if whole_days > OPEN_DAYS_PER_WEEK: | |
whole_days = OPEN_DAYS_PER_WEEK | |
ts %= DAY | |
whole_hours = ts // HOUR | |
whole_hours = whole_hours - OPEN_HOUR | |
if whole_hours < 0: | |
whole_hours = 0 | |
elif whole_hours > OPEN_HOURS_PER_DAY: | |
whole_hours = OPEN_HOURS_PER_DAY | |
return ( | |
whole_weeks * OPEN_HOURS_PER_WEEK + | |
whole_days * OPEN_HOURS_PER_DAY + | |
whole_hours | |
) | |
def open_hours(ts_begin, ts_end): | |
return primitive(ts_end) - primitive(ts_begin) | |
if __name__ == '__main__': | |
ts_begin = datetime.datetime(2019, 1, 14, 12, 0, 0, tzinfo=datetime.timezone.utc) # Monday at 12.00 | |
ts_end = datetime.datetime(2019, 1, 16, 17, 0, 0, tzinfo=datetime.timezone.utc) # Wednesday at 17.00 | |
print(open_hours(ts_begin.timestamp(), ts_end.timestamp())) | |
# Two days + five hours = 2*14 + 5 = 33 hours |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment