Introduction to the Python Calendar Module

Introduction

Python has an built-in module named Calendar that contains useful classes and functions to support a variety of calendar operations. By default, the Calendar module follows the Gregorian calendar, where Monday is the first day (0) of the week and Sunday is the last day of the week (6).

In Python, datetime and time modules also provide low-level calendar-related functionalities. In addition to these modules, the Calendar module provides essential functions related to displaying and manipulating calendars.

To print and manipulate calendars, the Calendar module has 3 important classes: Calendar, TextCalendar, and HTMLCalendar. In this article, we will see how these classes can help implement a variety of calendar related functions.

Functionalities of the Calendar Module

To use the Calendar module, we need to first import the module using:

import calendar

Let's take a look at the list of useful functions in this module.

Printing Calendar for a Specific Month

We can print the calendar for a specific month, by using the below function:

calendar.month(yyyy, m, w, l)

The arguments passed to this function are the year (yyyy), month (m), date column width (w), and the number of lines per week (l), respectively. For example, let's use this function to print the calendar of March, 2019:

print ("Calendar of March 2019 is:")
print (calendar.month(2019, 3, 2, 1))

Output:

Calendar of March 2019 is:
     March 2019
Mo Tu We Th Fr Sa Su
             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

Printing Calendar for a Specific Year

We can print the calendar for a whole year, using the below function:

calendar.calendar(yyyy, w, l, c, m)

The above function returns the calendar for the entire year, for the year specified as an argument. The arguments passed to this function are the year (yyyy), date column width (w), number of lines per week (l), number of spaces between month's column (c), number of columns (m).

For example, to print the calendar of the year 2019, use:

print(calendar.calendar(2019, 2, 2, 6, 3))

Output:

January                   February                   March

Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su

    1  2  3  4  5  6                   1  2  3                   1  2  3

 7  8  9 10 11 12 13       4  5  6  7  8  9 10       4  5  6  7  8  9 10

14 15 16 17 18 19 20      11 12 13 14 15 16 17      11 12 13 14 15 16 17

21 22 23 24 25 26 27      18 19 20 21 22 23 24      18 19 20 21 22 23 24

28 29 30 31               25 26 27 28               25 26 27 28 29 30 31



       April                      May                       June

Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su

 1  2  3  4  5  6  7             1  2  3  4  5                      1  2

 8  9 10 11 12 13 14       6  7  8  9 10 11 12       3  4  5  6  7  8  9

15 16 17 18 19 20 21      13 14 15 16 17 18 19      10 11 12 13 14 15 16

22 23 24 25 26 27 28      20 21 22 23 24 25 26      17 18 19 20 21 22 23

29 30                     27 28 29 30 31            24 25 26 27 28 29 30



        July                     August                  September

Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su

 1  2  3  4  5  6  7                1  2  3  4                         1

 8  9 10 11 12 13 14       5  6  7  8  9 10 11       2  3  4  5  6  7  8

15 16 17 18 19 20 21      12 13 14 15 16 17 18       9 10 11 12 13 14 15

22 23 24 25 26 27 28      19 20 21 22 23 24 25      16 17 18 19 20 21 22

29 30 31                  26 27 28 29 30 31         23 24 25 26 27 28 29

                                                    30



      October                   November                  December

Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su

    1  2  3  4  5  6                   1  2  3                         1

 7  8  9 10 11 12 13       4  5  6  7  8  9 10       2  3  4  5  6  7  8

14 15 16 17 18 19 20      11 12 13 14 15 16 17       9 10 11 12 13 14 15

21 22 23 24 25 26 27      18 19 20 21 22 23 24      16 17 18 19 20 21 22

28 29 30 31               25 26 27 28 29 30         23 24 25 26 27 28 29

                                                    30 31

Note: Instead of using "print", we can alternately use calendar.prmonth() and calendar.pryear() functions to print the month and year calendars. These functions print the output on your terminal.

Checking for a Leap Year

We can use isleap() function to check if a year is a leap year or not. The year is passed as an argument to the function and the function returns True if the year is a leap, otherwise it returns False if the year is not a leap. Let's use this function to see if the year 2016 is leap:

calendar.isleap(2016)

Output:

True

Number of Leap Years within Range

It is also possible to check the number of leap years in a given range of years, specified as an argument to the below function:

calendar.leapdays(year1, year2)

The arguments passed to the function are 2 valid year values. This function returns the number of leap years between those years.

Example:

calendar.leapdays(2000, 2017)

Output:

5

As seen, there are 5 leap years between 2000 and 2017, hence the output is 5.

Return the Day of a Week

The weekday method takes 3 arguments, namely: year, month, and day. The function returns the day of a week, with Monday having an index of 0 and Sunday having an index of 6. For example:

calendar.weekday(2019, 3, 21)

Output:

3

As seen, this function returns index value "3", which is "Thursday".

Getting Abbreviated Weekday Names

The function weekheader takes an argument n, which specifies the number of characters for a particular weekday name and returns a header containing abbreviated weekday names.

For example:

print (calendar.weekheader(2))

Output:

Mo Tu We Th Fr Sa Su

Similarly,

print (calendar.weekheader(3))

Output:

Mon Tue Wed Thu Fri Sat Sun

Getting Number of Days in a Month

The monthrange function takes 2 arguments: year and month. This function returns a tuple containing the index of the day of the week in which the month starts and the number of days in the month.

For example:

print (calendar.monthrange(1983, 12))

Output:

{3,31}

Since the first day of December, 1983 was a Thursday, the function returns index value of Thursday as the first element of the tuple, and 31 since that is the number of days in December.

Get the Weeks in a Month

The monthcalendar function takes 2 arguments: year and month and returns a matrix, in which each row represents a week in that month.

For example:

print(calendar.monthcalendar(1983, 11))

Output:

[[0,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,19,30,0,0,0]]

As you can see, each week array begins with Monday and days outside of the month are represented with zeroes. So the first array indicates that the first day of the month is a Tuesday.

Modifying Default Settings

Default calendar settings can be modified to fit your needs. For example, the following script sets Monday as the first day of the week.

class calendar.calendar(firstweekday=0)

By default, calendars follow European convention, having Monday as the first day of the week and Sunday as the last day of the week. Also, the month January has the index value 1 and December has the index value 12.

Useful Methods of the Calendar Class

The following are some of the most useful methods of the calendar class.

The iterweekdays() Method

This method returns an iterator that contains a list of indexes for the days in a week.

For example:

import calendar

c = calendar.Calendar()
for i in c.iterweekdays():
    print (i, end=" ")

Output:

0 1 2 3 4 5 6

The itermonthdates() Method

The itermonthdates() takes 2 arguments: year and month. This function returns an iterator of all days of the given month. Also, all days before the start of the month and after the end of the month, required to get the complete week, are displayed.

Example:

import calendar

c = calendar.Calendar()
for i in c.itermonthdates (2019, 1):
    print (i, end=" ")

Output:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

2018-12-31 2019-01-01 2019-01-02 2019-01-03 ..............2019-02-03

The itermonthdays() Method

This method is similar to itermonthdates method, but it only returns the day numbers.

Example:

import calendar

c = calendar.Calendar()
for i in c.itermonthdays (2019, 1):
    print (i, end=" ")

Output:

0 1 2 3 4 5 6........ 31 0 0 0

As you can see, all days before the start of the month and after the end of the month to get the complete week are set to "0".

The itermonthdays2() Method

This method displays a tuple consisting of day and weekday numbers.

Example:

import calendar

c = calendar.Calendar()
for i in c.itermonthdays2 (2019, 1):
    print (i, end=" ")

Output:

(0,0) (1,1) (2,2) (3,3) (4,4) (5,5) (6,6) (7,0) (8,1) (9,2) ...........

The itermonthdays3() Method

This method is pretty similar to the itermonthdays3() method, except that it returns a tuple of year, month, and the day of the month.

Example:

import calendar

c = calendar.Calendar()
for i in c.itermonthdays3 (2019, 1):
    print (i, end=" ")

Output:

(2018,12,31) (2019,01,01) (2019,01,02).....(2019,01,31) (2019,02,01) (2019,02,02) (2019,02,03)

The monthdatescalendar() Method

This method takes year and month as arguments and returns a list of full weeks in the month. Each week is a list of 7 datetime.date objects.

Example:

import calendar

c = calendar.Calendar()
for i in c.monthdatescalendar (2019, 1):
    print (i, end=" ")

Output:

[datetime.date(2018, 12, 31), datetime.date(2019, 01, 01), datetime.date(2019, 01, 02), datetime.date(2019, 01, 03), datetime.date(2019, 01, 04), datetime.date(2019, 01, 05), datetime.date(2019, 01, 06)... datetime.date(2019, 02, 03)]
.....

The monthdays2calendar() Method

This function takes year and month as arguments and returns a list of weeks, with each week as 7 tuples of the day of month and day of the week.

Example:

import calendar

c = calendar.Calendar()
for i in c.monthdays2calendar (2019, 1):
    print(i, end=" ")

Output:

[(0,0) (1,1) (2,2) (3,3) (4,4) (5,5) (6,6)]
[(7,0) (8,1) (9,2) (10,3) (11,4) (12,5) (13,6)]
....

As you see, the first value of the tuple is the day of the month (0-31) and second value of the tuple is the week number (0-6)

The monthdayscalendar() Method

This method takes year and month as arguments and returns a list of full weeks, with each week being a list of days of a month.

Example:

import calendar

c = calendar.Calendar()
for i in c.monthdayscalendar(2019, 1):
    print (i, end=" ")

Sample Output:

[0, 1, 2 , 3, 4, 5, 6] [7, 8, 9, 10, 11, 12, 13]....[28, 29, 30, 31, 0, 0, 0]

The yeardatescalendar() Method

This function takes the year (yyyy) and the number of months in a month row (w). By default, w parameter is 3. The function returns a list of month rows, where days are datetime.date objects.

Example:

import calendar

c = calendar.Calendar()
for i in c.yeardatescalendar(2019, 3):
    print (i, end=" ")

Output:

[[[datetime.date(2018, 12, 31), datetime.date(2019, 1, 1), datetime.date(2019, 1, 2), datetime.date(2019, 1, 3), datetime.date(2019, 1, 4), datetime.date(2019, 1, 5), datetime.date(2019, 1, 6)], [datetime.date(2019, 1, 7), datetime.date(2019, 1, 8), datetime.date(2019, 1, 9), datetime.date(2019, 1, 10), datetime.date(2019, 1, 11), datetime.date(2019, 1, 12), datetime.date(2019, 1, 13)], [datetime.date(2019, 1, 14), datetime.date(2019, 1, 15), datetime.date(2019, 1, 16), datetime.date(2019, 1, 17), datetime.date(2019, 1, 18), datetime.date(2019, 1, 19), datetime.date(2019, 1, 20)], [datetime.date(2019, 1, 21), datetime.date(2019, 1, 22), datetime.date(2019, 1, 23), datetime.date(2019, 1, 24), datetime.date(2019, 1, 25), datetime.date(2019, 1, 26), datetime.date(2019, 1, 27)], [datetime.date(2019, 1, 28), datetime.date(2019, 1, 29), datetime.date(2019, 1, 30), datetime.date(2019, 1, 31), datetime.date(2019, 2, 1), datetime.date(2019, 2, 2), datetime.date(2019, 2, 3)]] ... ]

The yeardays2calendar() Method

This function takes the year (yyyy) and number of months we want in a month row (w). By default, the w parameter is 3. The function returns a list of weeks, as tuples of days of the month and the day of the week.

Example:

import calendar

c = calendar.Calendar()
for i in c.yeardays2calendar(2019, 3):
    print (i, end=" ")

Output:

[[[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)], [(7, 0), (8, 1), (9, 2), (10, 3), (11, 4), (12, 5), (13, 6)], [(14, 0), (15, 1), (16, 2), (17, 3), (18, 4), (19, 5), (20, 6)], [(21, 0), (22, 1), (23, 2), (24, 3), (25, 4), (26, 5), (27, 6)], [(28, 0), (29, 1), (30, 2), (31, 3), (0, 4), (0, 5), (0, 6)]], [[(0, 0), (0, 1), (0, 2), (0, 3), (1, 4), (2, 5), (3, 6)], [(4, 0), (5, 1), (6, 2), (7, 3), (8, 4), (9, 5), (10, 6)], [(11, 0), (12, 1), (13, 2), (14, 3), (15, 4), (16, 5), (17, 6)], [(18, 0), (19, 1), (20, 2), (21, 3), (22, 4), (23, 5), (24, 6)], [(25, 0), (26, 1), (27, 2), (28, 3), (0, 4), (0, 5), (0, 6)]], [[(0, 0), (0, 1), (0, 2), (0, 3), (1, 4), (2, 5), (3, 6)] ... ]]

The yeardayscalendar() Method

This function takes the year (yyyy) and the number of months we want in a month row (w). By default, w parameter is 3. The function returns a list of weeks as the day of the month.

Example:

import calendar

c = calendar.Calendar()
for i in c.yeardayscalendar(2019, 3):
    print (i, end=" ")

Output:

[[[0, 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, 0, 0, 0]], [[0, 0, 0, 0, 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, 0, 0, 0]], [[0, 0, 0, 0, 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]]] [[[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, 0, 0, 0, 0, 0]] ... ]]

The TextCalendar Class

The TextCalendar is used to generate plain text calendars. Similar to the Calendar class. This class takes a constructor where the first weekday is set to 0, by default. Let's look at the methods provided by the TextCalendar class.

The formatmonth() Method

This method takes 4 arguments namely: year, month, the width of days column (w), and a number of lines used by each week (l). This method returns a multi-line string.

Example:

import calendar

c = calendar.TextCalendar()
print(c.formatmonth(2019, 1))

This displays calendar of January, 2019.

Output:

    January 2019
Mo Tu We Th Fr Sa Su
    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

The prmonth() Method:

This method prints a month's calendar as returned by the formatmonth method. We can use this function to avoid the use of "print" function, to print the calendar on the terminal.

To print the January, 2019 calendar, use:

c.prmonth(2019, 1)

The formatyear() Method:

This method returns a "m" column calendar for the entire year. The arguments passed to this function are year (yyyy), date column width (w), number of lines per week (l), number of spaces between month's column (c), number of columns (m).

The LocaleTextCalendar class:

This is a sub-class of TextCalendar class. Its constructor takes an additional argument, locale. It will return month and weekday names, in the specified locale. We can create a text calendar object in our native language. We can fetch month or weekdays or other data to display calendar formatted from the local system, other than the current default one. Example:

import calendar

for name in calendar.month_name:
    print(name)

This will print the name of the months, as per the local system.

Output:

January
February
March
April
May
June
July
August
September
October
November
December

The HTMLCalendar Class:

This is similar to TextCalendar class, but, generates an HTML calendar. The constructor for this class has the firstweekday set to "0".

Below are some of the methods provided by the HTMLCalendar class.

The formatmonth() method:

This function displays the calendar of a month, in a HTML table format. We can display April, 2019 calendar as a HTML table, using:

hc = calendar.HTMLCalendar()
print(hc.formatmonth(2019, 4))

Output:

<table border="0" cellpadding="0" cellspacing="0" class="month">
<tr><th colspan="7" class="month">April 2019</th></tr>
<tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr>
<tr><td class="mon">1</td><td class="tue">2</td><td class="wed">3</td><td class="thu">4</td><td class="fri">5</td><td class="sat">6</td><td class="sun">7</td></tr>
<tr><td class="mon">8</td><td class="tue">9</td><td class="wed">10</td><td class="thu">11</td><td class="fri">12</td><td class="sat">13</td><td class="sun">14</td></tr>
<tr><td class="mon">15</td><td class="tue">16</td><td class="wed">17</td><td class="thu">18</td><td class="fri">19</td><td class="sat">20</td><td class="sun">21</td></tr>
<tr><td class="mon">22</td><td class="tue">23</td><td class="wed">24</td><td class="thu">25</td><td class="fri">26</td><td class="sat">27</td><td class="sun">28</td></tr>
<tr><td class="mon">29</td><td class="tue">30</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr>
</table>

The formatyear() method:

This method takes year and number of months in a row (w) as arguments and prints the entire year's calendar as an HTML table. By default, the width is set to 3. We can display 2019 calendar as a HTML table using:

hc = calendar.HTMLCalendar()
print(hc.formatyear(2019, 4))

The formatyearpage() method:

This method takes a year, number of months in a row (w), cascading style sheet (CSS), and encoding, as arguments. The css and encoding arguments can be set to None, in case we do not use CSS and encoding. This function displays an entire year's calendar as an HTML page having default width of 3. We can print 2019 year's calendar as a HTML page using:

hc = calendar.HTMLCalendar()
print(hc.formatyearpage(2019, 3, css=None, encoding=None))
b'<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html>\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n<title>Calendar for 2019</title>\n</head>\n<body>\n<table border="0" cellpadding="0" cellspacing="0" class="year">\n<tr><th colspan="3" class="year">2019</th></tr><tr><td><table border="0" cellpadding="0" cellspacing="0" class="month">\n<tr><th colspan="7" class="month">January</th></tr>\n<tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr>\n<tr><td class="noday">&nbsp;</td><td class="tue">1</td><td class="wed">2</td><td class="thu">3</td><td class="fri">4</td><td class="sat">5</td><td class="sun">6</td></tr> ... </table></body>\n</html>\n'

The HTMLCalendar output looks similar to the plain text version, but it is wrapped with HTML tags. The cell of the HTML table contains a class attribute corresponding to the day of the week. Therefore, the HTML calendar can be styled through CSS.

The LocaleHTMLCalendar Class

This is a subclass of the HTMLCalendar class. Its constructor takes an additional argument, locale. It will return month and weekday names, in the specified locale as an HTML table. We can create a text calendar object in our native language. For example, we can generate the April 2019 calendar as an HTML table in 'en_AU' locale using:

import calendar

cal = calendar.LocaleHTMLCalendar(locale='en_AU.utf8')
print(cal.formatmonth(2019, 4))

Output:

<table border="0" cellpadding="0" cellspacing="0" class="month">
<tr><th colspan="7" class="month">April 2019</th></tr>
<tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr>
<tr><td class="mon">1</td><td class="tue">2</td><td class="wed">3</td><td class="thu">4</td><td class="fri">5</td><td class="sat">6</td><td class="sun">7</td></tr>
<tr><td class="mon">8</td><td class="tue">9</td><td class="wed">10</td><td class="thu">11</td><td class="fri">12</td><td class="sat">13</td><td class="sun">14</td></tr>
<tr><td class="mon">15</td><td class="tue">16</td><td class="wed">17</td><td class="thu">18</td><td class="fri">19</td><td class="sat">20</td><td class="sun">21</td></tr>
<tr><td class="mon">22</td><td class="tue">23</td><td class="wed">24</td><td class="thu">25</td><td class="fri">26</td><td class="sat">27</td><td class="sun">28</td></tr>
<tr><td class="mon">29</td><td class="tue">30</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr>
</table>

Conclusion

In this tutorial, we discussed the use of different classes and sub-classes of Calendar module in Python for working with dates to manage week/month/year oriented values. We also discussed the use of functions in the Python Calendar module. Along with this, we also implemented the TextCalendar and HTMLCalendar classes to produce pre-formatted output. I hope the tutorial was informative!

Last Updated: April 16th, 2019
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

Ā© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms