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.

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.

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

Related Articles

Back to top button

Get Python Course
worth 499$ for FREE!

Offer valid for 1st 20 seats only, Hurry up!!

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

H2kinfosys Blog will use the information you provide on this form to be in touch with you and to provide updates and marketing.