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.
Print a month’s 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.
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.
- Firstly, check its divisibility by 4, if it’s divisible then follow the next steps, otherwise, it is not a leap year.
- If the no. is divisible by 400, then definitely it’s a leap year. If not, check its divisibility by 100.
- 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).
>>> calendar.weekday(2020, 5, 30)
It returns 5 for May 5th, 2020 which is Saturday.
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.
The HTMLCalendar class can be used to generate HTML calendars.
HTML year calendar
The format year method of the HTMLCalendar class returns the HTML string of the calendar as a table. I am using this method to get the HTML code of the calendar and writing it to an HTML file. This method also requires the year as the argument to the function.
I am writing the output to an HTML file in the above code. The HTML code will look like this.
If we run this HTML file in any of our browsers, the output will look like this.
which is exactly identical to what we print in the terminal directly using the prcal() method.
To get only the HTML code of a month’s calendar instead of an entire year, we can use the formatmonth() month to get the HTML string and write it to an HTML file.
This will give us the HTML code of a month in a year.
Hope this article was helpful. Happy coding!