Skip to content

Instantly share code, notes, and snippets.

@kwatch
Last active December 26, 2016 05:29
Show Gist options
  • Save kwatch/f3aa40869ed92715ec2315c771fcac07 to your computer and use it in GitHub Desktop.
Save kwatch/f3aa40869ed92715ec2315c771fcac07 to your computer and use it in GitHub Desktop.
calendar
# -*- coding: utf-8 -*-
from datetime import date, timedelta
class Calendar(object):
def __init__(self, year, month):
self.year = year
self.month = month
def each_week(self):
week = [None] * self._nspaces()
for i in range(1, self._ndays()+1):
week.append(i)
if len(week) == 7:
yield week
week = []
if week:
n = 7 - len(week)
week.extend([None] * n)
yield week
def render_text(label):
buf = []; add = buf.append
self = "%s/%s" % (self.year, self.month)
header = "Su Mo Tu We Th Fr Sa"
add(label.center(len(header)))
add(header)
cell = lambda i: " " if i is None else "%2d" % i
for week in self.each_week():
add(" ".join( cell(i) for i in week ))
add("")
return "\n".join(buf)
def render_html(self):
buf = []; add = buf.append
add( "<table class=\"calendar\">")
add( " <caption>%s/%s</caption>" % (self.year, self.month))
add( " <thead>")
add( " <th>Su</th><th>Mo</th><th>Tu</th><th>We</th><th>Th</th><th>Fr</th><th>Sa</th>")
add( " </thead>")
add( " <tbody>")
for week in self.each_week():
add( " <tr>")
for x in week:
add(" <td>%s</td>" % (i or '&nbsp;'))
add( " </tr>")
add( " </tbody>")
add( "</table>")
add("")
return "\n".join(buf)
def _ndays(self):
yr, mo = self.year, self.month+1
if mo == 13:
yr, mo = yr+1, 1
last_date = date(yr, mo, 1) - timedelta(days=1)
return last_date.day
def _nspaces(self):
first_date = date(self.year, self.month, 1)
first_wday = first_date.weekday() # Mo: 0, Tu: 1, We: 2, ..., Sa: 5, Su: 6
return (first_wday + 1) % 7 # Mo: 1, Tu: 2, We: 3, ..., Sa: 6, Su: 0
print(Calendar(2016, 2).render_html())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment