"""Calendar printing functions
Note when comparing these calendars to the ones printed by cal(1): By
default, these calendars have Monday as the first day of the week, and
Sunday as the last (the European convention). Use setfirstweekday() to
set the first day of the week (0=Monday, 6=Sunday)."""
from itertools import repeat
__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
"firstweekday", "isleap", "leapdays", "weekday", "monthrange",
"monthcalendar", "prmonth", "month", "prcal", "calendar",
"timegm", "month_name", "month_abbr", "day_name", "day_abbr",
"Calendar", "TextCalendar", "HTMLCalendar", "LocaleTextCalendar",
"LocaleHTMLCalendar", "weekheader"]
# Exception raised for bad input (with string parameter for details)
# Exceptions raised for bad input
class IllegalMonthError(ValueError):
def __init__(self, month):
return "bad month number %r; must be 1-12" % self.month
class IllegalWeekdayError(ValueError):
def __init__(self, weekday):
return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday
# Constants for months referenced later
# Number of days per month (except for February in leap years)
mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# This module used to have hard-coded lists of day and month names, as
# English strings. The classes following emulate a read-only version of
# that, but supply localized names. Note that the values are computed
# fresh on each call, in case the user changes locale between calls.
_months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
_months.insert(0, lambda x: "")
def __init__(self, format):
def __getitem__(self, i):
return [f(self.format) for f in funcs]
return funcs(self.format)
# January 1, 2001, was a Monday.
_days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]
def __init__(self, format):
def __getitem__(self, i):
return [f(self.format) for f in funcs]
return funcs(self.format)
# Full and abbreviated names of weekdays
day_name = _localized_day('%A')
day_abbr = _localized_day('%a')
# Full and abbreviated names of months (1-based arrays!!!)
month_name = _localized_month('%B')
month_abbr = _localized_month('%b')
(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
"""Return True for leap years, False for non-leap years."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
"""Return number of leap years in range [y1, y2).
return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
def weekday(year, month, day):
"""Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
return datetime.date(year, month, day).weekday()
def monthrange(year, month):
"""Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
raise IllegalMonthError(month)
day1 = weekday(year, month, 1)
ndays = mdays[month] + (month == February and isleap(year))
Base calendar class. This class doesn't do any formatting. It simply
provides data to subclasses.
def __init__(self, firstweekday=0):
self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday
def getfirstweekday(self):
return self._firstweekday % 7
def setfirstweekday(self, firstweekday):
self._firstweekday = firstweekday
firstweekday = property(getfirstweekday, setfirstweekday)
Return an iterator for one week of weekday numbers starting with the
for i in range(self.firstweekday, self.firstweekday + 7):
def itermonthdates(self, year, month):
Return an iterator for one month. The iterator will yield datetime.date
values and will always iterate through complete weeks, so it will yield
dates outside the specified month.
date = datetime.date(year, month, 1)
# Go back to the beginning of the week
days = (date.weekday() - self.firstweekday) % 7
date -= datetime.timedelta(days=days)
oneday = datetime.timedelta(days=1)
# Adding one day could fail after datetime.MAXYEAR
if date.month != month and date.weekday() == self.firstweekday:
def itermonthdays2(self, year, month):
Like itermonthdates(), but will yield (day number, weekday number)
tuples. For days outside the specified month the day number is 0.
for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday):
def itermonthdays(self, year, month):
Like itermonthdates(), but will yield day numbers. For days outside
the specified month the day number is 0.
day1, ndays = monthrange(year, month)
days_before = (day1 - self.firstweekday) % 7
yield from repeat(0, days_before)
yield from range(1, ndays + 1)
days_after = (self.firstweekday - day1 - ndays) % 7
yield from repeat(0, days_after)
def monthdatescalendar(self, year, month):
Return a matrix (list of lists) representing a month's calendar.
Each row represents a week; week entries are datetime.date values.
dates = list(self.itermonthdates(year, month))
return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
def monthdays2calendar(self, year, month):
Return a matrix representing a month's calendar.
Each row represents a week; week entries are
(day number, weekday number) tuples. Day numbers outside this month
days = list(self.itermonthdays2(year, month))
return [ days[i:i+7] for i in range(0, len(days), 7) ]
def monthdayscalendar(self, year, month):
Return a matrix representing a month's calendar.
Each row represents a week; days outside this month are zero.
days = list(self.itermonthdays(year, month))
return [ days[i:i+7] for i in range(0, len(days), 7) ]
def yeardatescalendar(self, year, width=3):
Return the data for the specified year ready for formatting. The return
value is a list of month rows. Each month row contains up to width months.
Each month contains between 4 and 6 weeks and each week contains 1-7
days. Days are datetime.date objects.
self.monthdatescalendar(year, i)
for i in range(January, January+12)
return [months[i:i+width] for i in range(0, len(months), width) ]
def yeardays2calendar(self, year, width=3):
Return the data for the specified year ready for formatting (similar to
yeardatescalendar()). Entries in the week lists are
(day number, weekday number) tuples. Day numbers outside this month are
self.monthdays2calendar(year, i)
for i in range(January, January+12)
return [months[i:i+width] for i in range(0, len(months), width) ]
def yeardayscalendar(self, year, width=3):
Return the data for the specified year ready for formatting (similar to
yeardatescalendar()). Entries in the week lists are day numbers.
Day numbers outside this month are zero.
self.monthdayscalendar(year, i)
for i in range(January, January+12)
return [months[i:i+width] for i in range(0, len(months), width) ]
class TextCalendar(Calendar):
Subclass of Calendar that outputs a calendar as a simple plain text
similar to the UNIX program cal.
def prweek(self, theweek, width):
Print a single week (no newline).
print(self.formatweek(theweek, width), end=' ')
def formatday(self, day, weekday, width):
s = '%2i' % day # right-align single-digit days
def formatweek(self, theweek, width):
Returns a single week in a string (no newline).
return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek)
def formatweekday(self, day, width):
Returns a formatted week day name.
return names[day][:width].center(width)
def formatweekheader(self, width):
Return a header for a week.
return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays())
def formatmonthname(self, theyear, themonth, width, withyear=True):
Return a formatted month name.
s = "%s %r" % (s, theyear)
def prmonth(self, theyear, themonth, w=0, l=0):
Print a month's calendar.
print(self.formatmonth(theyear, themonth, w, l), end='')
def formatmonth(self, theyear, themonth, w=0, l=0):
Return a month's calendar string (multi-line).
s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
s += self.formatweekheader(w).rstrip()
for week in self.monthdays2calendar(theyear, themonth):
s += self.formatweek(week, w).rstrip()
def formatyear(self, theyear, w=2, l=1, c=6, m=3):
Returns a year's calendar as a multi-line string.
colwidth = (w + 1) * 7 - 1
a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip())
header = self.formatweekheader(w)
for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
months = range(m*i+1, min(m*(i+1)+1, 13))
names = (self.formatmonthname(theyear, k, colwidth, False)
a(formatstring(names, colwidth, c).rstrip())
headers = (header for k in months)
a(formatstring(headers, colwidth, c).rstrip())
# max number of weeks for this row
height = max(len(cal) for cal in row)
weeks.append(self.formatweek(cal[j], w))
a(formatstring(weeks, colwidth, c).rstrip())
def pryear(self, theyear, w=0, l=0, c=6, m=3):
"""Print a year's calendar."""
print(self.formatyear(theyear, w, l, c, m))
class HTMLCalendar(Calendar):
This calendar returns complete HTML pages.
# CSS classes for the day <td>s
cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
def formatday(self, day, weekday):
Return a day as a table cell.
return '<td class="noday"> </td>' # day outside month
return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)
def formatweek(self, theweek):
Return a complete week as a table row.
s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
def formatweekday(self, day):
Return a weekday name as a table header.
return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day])
def formatweekheader(self):
Return a header for a week as a table row.
s = ''.join(self.formatweekday(i) for i in self.iterweekdays())
def formatmonthname(self, theyear, themonth, withyear=True):
Return a month name as a table row.
s = '%s %s' % (month_name[themonth], theyear)
s = '%s' % month_name[themonth]
return '<tr><th colspan="7" class="month">%s</th></tr>' % s
def formatmonth(self, theyear, themonth, withyear=True):
Return a formatted month as a table.
a('<table border="0" cellpadding="0" cellspacing="0" class="month">')
a(self.formatmonthname(theyear, themonth, withyear=withyear))
a(self.formatweekheader())
for week in self.monthdays2calendar(theyear, themonth):
def formatyear(self, theyear, width=3):
Return a formatted year as a table of tables.
a('<table border="0" cellpadding="0" cellspacing="0" class="year">')
a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))
for i in range(January, January+12, width):
months = range(i, min(i+width, 13))
a(self.formatmonth(theyear, m, withyear=False))
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):
Return a formatted year as a complete HTML page.
encoding = sys.getdefaultencoding()
a('<?xml version="1.0" encoding="%s"?>\n' % encoding)
a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)
a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)
a('<title>Calendar for %d</title>\n' % theyear)
a(self.formatyear(theyear, width))
return ''.join(v).encode(encoding, "xmlcharrefreplace")
def __init__(self, locale):
self.oldlocale = _locale.getlocale(_locale.LC_TIME)
_locale.setlocale(_locale.LC_TIME, self.locale)
def __exit__(self, *args):
_locale.setlocale(_locale.LC_TIME, self.oldlocale)