All IT Courses 50% Off
Python Tutorials

Python CALENDAR Tutorial with Example

Calendars are very easy to use in Python. Calendars are used in many applications like inventory management systems in which you have to go back and forth between different dates.

Let’s take a look at an example of how to print the January month Calendar in Python.

import calendar
calen = calendar.TextCalendar(calendar.SUNDAY)
str = calen.formatmonth(2020,1)
print(str)

The output will be.

Python CALENDAR Tutorial with Example

calen = calendar.TextCalendar(calendar.SUNDAY)

The calendar.SUNDAY will set the format of the calendar. As you can see above that the calendar starts with Sunday.

All IT Courses 50% Off
str = calen.formatmonth(2020,1)

Here “2020” is the year and “1” is the month

Printing Calendar in HTML

Developers usually need a calendar in HTML format to make changes in the look and feel. So let’s see how to print the calendar in HTML format.

import calendar
calen = calendar.HTMLCalendar(calendar.SUNDAY)
str = calen.formatmonth(2020,1)
print(str)

Python CALENDAR Tutorial with Example

calen = calendar.HTMLCalendar(calendar.SUNDAY)

The only thing that changed in the code is the above line in which we first used TextCalendar and now using HTMLCalender.

Loop over the Month

Sometimes we need to loop over the month days. For that purpose Let’s take a look at the how-to loop over the month of January 2020.

import calendar
calen = calendar.TextCalendar(calendar.SUNDAY)
for i in calen.itermonthdays(2020,1):
print(i)

Python CALENDAR Tutorial with Example

Using loop we can also print the month name.

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

Python CALENDAR Tutorial with Example

Let’s print the day names using a loop.

import calendar
for i in calendar.day_name:
print(i)

Python CALENDAR Tutorial with Example

Python CALENDAR Tutorial with Example

Facebook Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button