Example 3: Calendar

The calendar module is useful to output calendars and provides additional useful functions related to the calendar. To use the classes in the calendar module, we need to import the calendar module first.


import calendar

The class calendar.TextCalendar can be used to generate plain text calendars.
Constructor: calendar.TextCalendar([firstweekday]).The argument firstweekday is an integer specifying the first day of the week. 0 is Monday (the default), 6 is Sunday.
It has the following instance methods:

Method Description
formatmonth(theyear, themonth[, w[, l]]) Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use.
prmonth(theyear, themonth[, w[, l]]) Print a month’s calendar as returned by formatmonth().
formatyear(theyear[, w[, l[, c[, m]]]]) Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively.
pryear(theyear[, w[, l[, c[, m]]]]) Print the calendar for an entire year as returned by formatyear().

For example, with the following code, we can print the calendar for October 2014:

my_calendar = calendar.TextCalendar()
print my_calendar.formatmonth(2014,10) # the result is shown in the image below
##The following code can print the calendar for the year 2014
my_calendar.pryear(2014)

oct

More information about classes in the calendar module see: https://docs.python.org/2/library/calendar.html