Python calendar module

Boost Your Career with In-demand Skills - Start Now!

Python contains an inbuilt module known as the calendar module for handling operations relating to calendars. The calendar module gives calendars as outputs and also includes other programs and codes involving calendars. All the functions and classes within the calendar module make use of the standard Gregorian calendar. As a default setting these calendars have Monday as the first day of the week and Sunday as the last.

What is python calendar module?

Python calendar module allows you to work with calendars and perform functions on calendars. The calendar by default starts on Monday(=0) and ends on Sunday(=6).

In this tutorial, we are using the Gregorian calendar that extends infinitely in both ways. The ISO declares how to interrupt zero and negative years. Year 0 is ‘1 BC’, year-1 is ‘2 BC’ and so on.

Import the calendar module using the following command

Import calendar as cd

Python calendar class

The constructor for the calendar class is as follows:

class calendar.Calendar(firstweekday=0)

This creates an object of the calendar and begins at the day we decide. By default it begins on Monday which is set to 0.

Work with the calendar module

Step 1: execute the code

Type the following code in your editor and click run to execute the results.

import calendar
c=calendar.TextCalendar(calendar.SUNDAY)
str=c.formatmonth(2025,1)
print(str)

This prints the calendar of January month of 2025.

  • In the first line, we are importing in the calendar library without which it is impossible to execute the code easily.
  • In the second line, we are telling the interpreter to create a text calendar
  • In the third line, we are creating a calendar for the year 2025 and the month of January
  • Print str command prints the calendar as output

Step 2:

We can also print the calendar in HTML format, this feature is very helpful to the developers in case they want to make edits to the look of the calendar. You can edit the data inside the HTML file if you need.

import calendar
hc=calendar.HTMLCalendar(calendar.THURSDAY)
str=hc.formatmonth(2025,1)
print(str)

This prints the calendar of January month of 2025 in HTML format.

Step 3:

c.itermonthday(2025, 4) allows you to loop through the days. It returns the total number of days in the month.

You can also get data from your personal local systems, such as months or weekdays

import calendar 
for name in calendar.month_name:
    print(name)

This gives names of all months in the output.

Step 4:

You can get the list of the specific day for the entire year. Consider the example where there is an audit day on the monday of every week. You can use this code to get date for each first monday of the month:

import calendar 
for month in range (1,13):
    mycalen=calendar.monthcalendar(2022, month)
    week1=mycalen[0]
    week2=mycalen[1]
    if week1[calendar.MONDAY]!=0:
        auditday=week1[calendar.MONDAY]
    else:
        auditday=week2[calendar.MONDAY]
    print("%10s %2d" % (calendar.month_name[month],auditday))

Output:

January      3
February     7
March          7
April             4
May              2
June             6
July              4
August         1
September  5
October       3
November   7
December   5

Let us look at few other sample codes

Example 1

Display calendar of the given month:

Import calendar
yy=2017
mm=11
print(calendar.month(yy,mm))

In the above piece of code, we import the calendar module and declare the year and month of which we want to print the calendar. It gives calendar of November month of 2017.

Example 2

Display calendar of any given year:

Import calendar
print(calendar.calendar(2022,2,1,6))

It displays calendar of 2022.

See the days of the week

weekheader() method allows you to print the days of the week and it begins with monday by default.

You can give a header argument to the weekheader() method. This integer tells the number or length of the string

import calendar
print(calendar.weekheader(4))

Output:

Mon  Tue  Wed   Thu  Fri  Sat  Sun

setfirstweekday() method allows you to change the default Monday to a weekday fo your choice.

See if a year is leap year or not

Let us write a code to check if the given year is a leap year or not. The isleap() method allows you to check this. We can pass the year as an argument and the code prints true or false accordingly.

import calendar
print(calendar.isleap(2023))

Output:

False

Check the number of leap days between a specific range of years

leapdays() method to check the number of leap days between to different years that we pass as arguments of the method.

import calendar
checkleap= calendar.leapdays(2020, 2024)
print(checkleap)

Output:

1

Class calendar.calendar(firstweekday=0)

This creates a calendar object. The firstweekday is an integer indicating the first day of the week. Monday is 0 and Sunday is 6.

A calendar object contains many methods for calendar data formatting. The subclasses format the calendars.

Function  Description 
iterweekdays Returns an iterator for the numbers of week days for one week
itermonthdates(year, month) Returns an iterator for the given month in the given year
itermonthdates(year, month) Gives an iterator for the month month for the year year but does not restrict itself to the datetime.date range
monthdatescalendar() Returns a complete list of the weeks in the given month of the year in the form of full weeks
monthdayscalendar() Gives a list of the weeks in the given month of the year. Weeks are lists of seven days
yeardatescalendar() Gets a list of the weeks of the month in the year as full weeks
yeardayscalendar() Gets data of the specific year. Weeks lists contains day numbers,

Class calendar.Textcalendar

This class generates plain text calendars. The constructor for this class has the following syntax:

class calendar.Textcalendar(firstweekday=0)

It has the following methods:

Method name  Method description
formatmonth(theyear, themonth,w=0,L=0) Get a calendar with a multi-string. W is width of the date columns, L is number of lines each week uses
prmonth(theyear, themonth, w=0, L=0) Prints a calendar that formatmonth() returns
formatyear(theyear, w=2,L=1,c=6,m=3) Gives an m-column calendar for the entire year as a multistring. C is number of spaces between month columns
pryear(theyear, w=2, L=1, c=6, m=3) Get a calendar for the entire year that formatyear() returns 

Examples of the method in the TextCalendar class:

1. formatmonth(theyear, themonth, w=0, L=0)

We obtain the calendar of the month in the form of a multiline string. W is the width of the centred date columns, l is the number of lines each week can use. We need to give the value of the first weekday

import calendar as cd
t=cd.TextCalendar(0)
print(t.formatmonth(2018,12))

Output:

December 2018Mo 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

2. prmonth(theyear, themonth, [w=0,l=0]

The above code can simply also be done with the prmonth() method

import calendar as cd
t=cd.TextCalendar(0)
t.prmonth(2018,12)

Output
December 2018
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

3. formatyear(theyear, [w=2, l=1, c=6, m=3])

This gives the calendar for an entire year. W stands for width, l stands for lines per week, c stands for the number of spaces between month columns. We need to specify firstweekday.

import calendar as cd
t=cd.TextCalendar(0)
print(t.formatyear(2018,5)) #sets w=5 and m is 3 by default
print(t.formatyear(2018,m=5))

4. pryear(theyear, [w=2, l=1, c=, m=3])

Prints the whole year calendar same as above

import calendar as cd
t=cd.TextCalendar(0)
t.pryear(2018,m=5)

Class calendar.HTMLcalendar

This class creates HTML calendars. The syntax for the constructor is as follows:

Class calendar.HTMLCalendar(firstweekday=0)

1. formatmonth(theyear, themonth, withyear=True)

This method prints the calendar for the month in HTML table format

import calendar as cd
h=cd.HTMLCalendar()
print(h.formatmonth(2018,12))

Output:

<table border=”0″ cellpadding=”0″ cellspacing=”0″ class=”month”> <tr><th colspan=”7″ class=”month”>December 2018</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=”noday”>&nbsp;</td><td class=”noday”>&nbsp;</td><td class=”noday”>&nbsp;</td><td class=”noday”>&nbsp;</td><td class=”noday”>&nbsp;</td><td class=”sat”>1</td><td class=”sun”>2</td></tr> <tr><td class=”mon”>3</td><td class=”tue”>4</td><td class=”wed”>5</td><td class=”thu”>6</td><td class=”fri”>7</td><td class=”sat”>8</td><td class=”sun”>9</td></tr> <tr><td class=”mon”>10</td><td class=”tue”>11</td><td class=”wed”>12</td><td class=”thu”>13</td><td class=”fri”>14</td><td class=”sat”>15</td><td class=”sun”>16</td></tr> <tr><td class=”mon”>17</td><td class=”tue”>18</td><td class=”wed”>19</td><td class=”thu”>20</td><td class=”fri”>21</td><td class=”sat”>22</td><td class=”sun”>23</td></tr> <tr><td class=”mon”>24</td><td class=”tue”>25</td><td class=”wed”>26</td><td class=”thu”>27</td><td class=”fri”>28</td><td class=”sat”>29</td><td class=”sun”>30</td></tr> <tr><td class=”mon”>31</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><td class=”noday”>&nbsp;</td></tr> </table>

2. formatyear(theyear, width=3)

Prints the HTML table for the complete year calendar. The width specifies the number of months in a row and by default it is 3.

import calendar as cd
h=cd.HTMLCalendar()
print(h.formatyear(2018,3))

3. formatyearpage(theyear, width=3, css=’calendar.css’, encoding=None)

Prints the calendar for the whole year as an HTML page and the default width is set to 3. If we do not make use of the css file we can type none instead.

import calendar as cd
h=cd.HTMLCalendar()
print(h.formatyearpage(2020,css=None))

It contains the following methods:

Method name Method description 
formatmonth(theyear, themonth, withyear=True) Get the calendar for the month in the form of an HTML table. If withyear is true then it includes the year in the header if not then use the month name.
formatyear(theyear, width=3) Gets the calendar of the year as an HTML table. Width tells about the number of months in the row.
formatyearpage(theyear, width=3, css=’calendar.css’, encoding=None ) Gets the calendar of the complete year as an HTML page. Css contains the names of the cascading style to use. Encoding stores the encoding to use for the output.

Simple TextCalendar class:

For building simple text calendars, the calendar module offers the following functions:

Method name Method description 
setfirstweekday() Sets the first weekday from where the week begins
firstweekday() Returns first weekday number. Monday is 0 by default
isleap() Checks if the given year is leap year
leapdays() Returns the number of leap days between the given years
weekday() Returns the weekday number of the date passed
weekheader() Returns header of abbreviated weekday names
monthrange() Returns the beginning day of the week and number of days in the month
monthcalendar() Prints the month calendar 
prmonth() Also prints the month calendar 
month() Returns the month of the given year
prcal() Prints the calendar of the specific year
calendar() Displays the year

Conclusion

In this article we look briefly into the Python calendar module. We look at some of its important classes and their prominent methods. We hope our explanation was easy to understand.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google | Facebook


PythonGeeks Team

The PythonGeeks Team offers industry-relevant Python programming tutorials, from web development to AI, ML and Data Science. With a focus on simplicity, we help learners of all backgrounds build their coding skills.

Leave a Reply

Your email address will not be published. Required fields are marked *