-
Notifications
You must be signed in to change notification settings - Fork 0
/
schedule.py
74 lines (67 loc) · 2.54 KB
/
schedule.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from functools import lru_cache
import tzlocal
from datetime import datetime, timedelta
from dateutil import parser
class ScheduleManager(object):
def __init__(self, config, timezone=None):
self.config = config
if timezone == None:
self.timezone = tzlocal.get_localzone()
else:
self.timezone = timezone
@staticmethod
@lru_cache(maxsize=8, typed=True)
def _calc_sched(day_sched):
# If day isn't defined, 9-5. If defined and empty, not on that day
if not day_sched:
return None
day_sched = [parser.parse(x).time() for x in day_sched.split('-')]
return day_sched
def _getsched(self):
if 'schedule' in self.config:
# Missing days have no active hours
schedule = self.config['schedule'] or {}
schedule = [schedule.get(("mon", "tue", "wed", "thu", "fri", "sat", "sun")[x]) for x in range(7)]
else:
# Default schedule is 9-5 weekdays
schedule = ['9-17']*5 + ['']*2
return [self._calc_sched(d) for d in schedule]
def get_next_sleep(self):
# If schedule key exists and is empty, then there is no schedule
schedule = self._getsched()
if schedule == [None]*7:
return 0
sleep_day = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
sched = None
while True:
sched = schedule[sleep_day.weekday()]
if sched is None:
sleep_day -= timedelta(1)
else:
break
return self.timezone.localize(sleep_day.combine(sleep_day, sched[1]))
def get_next_wake(self):
# If schedule key exists and is empty, then there is no schedule
schedule = self._getsched()
if schedule == [None]*7:
return 0
wake_day = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(1)
sched = None
while True:
sched = schedule[wake_day.weekday()]
if sched is None:
wake_day += timedelta(1)
else:
break
return self.timezone.localize(wake_day.combine(wake_day, sched[0]))
def live_now(self, now=None):
if now == None:
now = datetime.now(tz=self.timezone)
schedule = self._getsched()
if schedule == [None]*7:
return True
sched = schedule[now.weekday()]
now = now.time()
if sched is None:
return False
return sched[0] <= now <= sched[1]