Calendar module in python

The calendar module in python enables us to print calendars on the terminal and other cool functions with the calendar.

Import the calendar module to access all these functions.

import calendar

The prmonth() method helps us to print a month’s calendar. It requires the year and the month in the form of integers as arguments.

import calendar
calendar.prmonth(2001,9)

Check leap years

We can check whether a given year is a leap year by using the isleap() method of the calendar. This method takes a year as an argument and returns “True” or “False”.

If you think only dividing the year by 4 gives you a leap year, then you are absolutely wrong. A year is a leap year only if it satisfies the following three conditions:

  1. Firstly, check its divisibility by 4, if it’s divisible then follow the next steps, otherwise, it is not a leap year.
  2. If the no. is divisible by 400, then definitely it’s a leap year. If not, check its divisibility by 100.
  3. If the no. is divisible by 100, then it is not a leap year.

So, instead of writing all these conditions, we can just use this method.

Get the day of a date

If we wish to know what day a particular date is we can use the weekday() method. This method takes a day, month, and a year as arguments. This will return an integer value from 0–6. 0 -Monday, 1 — Tuesday, … 6 — Sunday, and so on.

It receives arguments in the format of (year, month, day).

It returns 2 for April 4th, 2021 which is Wednesday.

Print entire year

We can print an entire year using the prcal() method. This method takes the year as an argument. We can also specify the column width and spacing in the arguments.