-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdatemagic.py
176 lines (156 loc) · 6.6 KB
/
datemagic.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#from cgitb import html
from time import localtime, mktime, time
from datetime import datetime, date
from calendar import HTMLCalendar
import pytz
def sec_to_date(sec, option=0):
'''str_date returns in the format YY-M-D'''
ds = localtime(sec)
str_date = f'{str(ds.tm_year)[2:]}-{ds.tm_mon}-{ds.tm_mday} {ds.tm_hour}:{ds.tm_min}'
if option==0:
return str_date.split()[0]
elif option==1:
return str_date
def year_start_unixtime():
today = date.today()
september_1st_this_year = date(today.year, 9, 1)
if today < september_1st_this_year:
# If today's date is before this year's September 1st, use last year's September 1st
september_1st = date(today.year - 1, 9, 1)
else:
# Use this year's August 1st
september_1st = september_1st_this_year
return int(mktime(september_1st.timetuple()))
def sec_to_weekday(epoch):
return datetime.fromtimestamp(epoch).strftime("%A")
def date_to_sec(str_date):
'''str_date should always be in the format YY-M-D
returns the current yy-m-d in unix epoch seconds since 1970'''
#ld = [int(n) for n in str_date.split('-')]
#'''adds 2000 to fix year-trimming in date-format to avoid mktime() crash'''
#date = datetime(2000 + ld[0], ld[1], ld[2])
#sec = int(mktime(date.timetuple()))
date_format = "%y-%m-%d"
date = datetime.strptime(str_date, date_format)
sec = int(date.timestamp())
return sec
def date_start_epoch(epoch):
'''Returns the unixtime of the start of the day, for +hour manipulation'''
dt = datetime.date(datetime.fromtimestamp(epoch))
return mktime(dt.timetuple())
def init_dates(today_d):
'''Returns a dictionary with todays date +/- 1 returned as string and epoch_s'''
today_s = date_to_sec(today_d)
yday_s = today_s-86400
yday_d = sec_to_date(yday_s)
morrow_s = today_s+86400
morrow_d = sec_to_date(morrow_s)
return { 'today': { 'string': today_s, 'date': today_d },
'yesterday': { 'string': yday_s, 'date': yday_d },
'tomorrow': { 'string': morrow_s, 'date': morrow_d }
}
def ics_zulu_to_se(date_str):
# parse the date string to a datetime object in UTC
dt_utc = datetime.strptime(date_str, '%Y%m%dT%H%M%SZ')
tz = pytz.timezone('Europe/Stockholm')
dt = dt_utc.replace(tzinfo=pytz.utc).astimezone(tz)
return dt.strftime('%Y%m%d %H%M')
def ics_date(dtstart, dtend):
sd, _, st = dtstart.partition(" ")
dtst = datetime(
int(sd[:4]),
int(sd[4:6]),
int(sd[6:8]),
int(st[:2]),
int(st[2:4]))
showsum = dtst.strftime('%y-%m-%d %H:%M')
ed, _, et = dtend.partition(" ")
dten = datetime(
int(ed[:4]),
int(ed[4:6]),
int(ed[6:8]),
int(et[:2]),
int(et[2:4])
)
showsum += dten.strftime('-%H:%M')
return showsum
def unixtime(option=0):
if option != 0:
return datetime.fromtimestamp(option)
else:
return int(time())
def check_book_epoch(epoch, minutes):
'''Booking possible if within # minutes of pod timeslot start'''
now_s = round(time())
if epoch > now_s:
return True
elif epoch < now_s and abs(epoch - now_s) < (minutes*60):
return True
else:
return False
def epoch_hr(epoch):
'''Checks if a timestamp is within a grace period of the booking-time'''
if isinstance(epoch, int) or isinstance(epoch, float):
return datetime.fromtimestamp(epoch).hour
elif epoch == 'HR':
return datetime.fromtimestamp(time()).hour
elif epoch == 'NOW':
return time()
def date_to_str():
'''Todays date but without the leading 2 digits in 2022'''
return str(date.today())[2:]
def endtimes(datestr, dur):
hr, m = map(int, datestr.split(':'))
hr += dur // 60
m += dur % 60
if m >= 60:
m -= 60
hr += 1
return f'{hr:02d}:{m:02d}'
def show_calendar(urldate, room, SITE_PREFIX):
class RoomCalendar(HTMLCalendar):
def __init__(self, url=[], today=[], *args, **kwargs):
super().__init__(*args, **kwargs)
self._today = today
self._url = url
def formatday(self, day, weekday):
_date = [int(x) for x in str(date.today())[2:].split('-')]
daystr = f'{self._url[0]}-{self._url[1]}-{day}'
url = f'{SITE_PREFIX}show/ROOM/'
if day == self._today and day == self._url[2] and _date[1] == self._url[1]:
return f'<td class="urltoday"><a href="{url}{daystr}" class="calurl">{day}</a></td>'
elif day == self._today and _date[1] == self._url[1]:
return f'<td class="today"><a href="{url}{daystr}" class="calurl">{day}</a></td>'
elif day == self._url[2]:
return f'<td class="urlday"><a href="{url}{daystr}" class="calurl">{day}</a></td>'
elif day == 0:
return '<td class="noday"> </td>'
else:
return f'<td class="wday"><a class="calurl" href="{url}{daystr}">{day}</a></td>'
urldate = [int(x) for x in urldate.split('-')]
today_date = datetime.now()
html_raw = RoomCalendar(url=urldate, today=today_date.day).formatmonth(2000+urldate[0], urldate[1], withyear=False)
html_output = ''
for line in html_raw.split('\n'):
if 'table' not in line:
if 'class="mon"' in line:
line = '<tr><th class="dh">M</th><th class="dh">T</th><th class="dh">W</th><th class="dh">T</th><th class="dh">F</th><th class="dh">S</th><th class="dh">S</th></tr>'
elif 'class="today"' in line:
line = line.replace('class="today"', 'class="today table-success"')
elif 'class="month"' in line:
if urldate[1] == 1:
prev_m = 12
urldate[0] -= 1
next_m = 2
elif urldate[1] == 12:
next_m = 1
urldate[0] += 1
prev_m = 11
else:
next_m = urldate[1]+1
prev_m = urldate[1]-1
line = line.replace('</th>', f'</th><th><a href="{SITE_PREFIX}show/{room}/{urldate[0]}-{next_m}-1"><i class="bi bi-caret-right-fill" style="color:black"></i></a></th>')
line = line.replace('<th colspan="7" class="month">', f'<th><a href="{SITE_PREFIX}show/{room}/{urldate[0]}-{prev_m}-1"><i class="bi bi-caret-left-fill" style="color:black"></i></a></th><th colspan="5" class="month">')
html_output += line
html_output = html_output.replace('ROOM', room)
return html_output