Skip to content

Instantly share code, notes, and snippets.

@NimaBavari
Created January 30, 2025 00:01
Show Gist options
  • Save NimaBavari/d01b03e4c20c8ce11d3e87259693401b to your computer and use it in GitHub Desktop.
Save NimaBavari/d01b03e4c20c8ce11d3e87259693401b to your computer and use it in GitHub Desktop.
Generates HTML string of the calendar of given month and year.
import math
def is_leap(year: int) -> bool:
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def residue_year(year: int) -> int:
return 2 if is_leap(year) else 1
def generate_calendar_html(month: int, year: int) -> str:
month_names = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
month_days = [
31,
29 if is_leap(year) else 28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
]
try:
days_in_month = month_days[month - 1]
except IndexError:
return "<h1>Month numbers must be between 1 and 12.</h1>"
month_name = month_names[month - 1]
total_residue = sum([residue_year(i) for i in range(1, year)]) + sum([month_days[i] for i in range(month - 1)])
day_of_week = total_residue % 7 + 1
num_rows = math.ceil((days_in_month + day_of_week - 1) / 7)
html = (
"""
<h1>%s</h1>
<table>
<tr>
<th>Mo</th>
<th>Tu</th>
<th>We</th>
<th>Th</th>
<th>Fr</th>
<th>Sa</th>
<th>Su</th>
</tr>
"""
% month_name
)
for row in range(1, num_rows + 1):
html += "<tr>"
if row == 1:
for cell in range(1, day_of_week):
html += "<td></td>"
for cell in range(day_of_week, 8):
curr_day_num = cell + 1 - day_of_week
html += "<td>%d</td>" % curr_day_num
else:
for cell in range(1, 8):
curr_day_num = (row - 1) * 7 + cell + 1 - day_of_week
if curr_day_num <= days_in_month:
html += "<td>%d</td>" % curr_day_num
else:
html += "<td></td>"
html += "</tr>"
html += "</table>"
return html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment