---
description: Calendar module in Python has the calendar class that allows the calculations based on date, month, and year. Learn how to print Text , HTML Calendar in python with examples.
title: Python calendar Module with Example
image: https://www.guru99.com/images/python-calendar.png
---

[Skip to content](#main)

**⚡ Smart Summary**

The calendar module in Python generates text and HTML calendars using the TextCalendar and HTMLCalendar classes. It performs date calculations based on the day, month, and year, and lets you customize the starting weekday for any month.

- 🔘 **Two calendar types:** The TextCalendar and HTMLCalendar classes produce plain-text and web-ready calendars for a chosen month or year.
- ☑️ **First weekday:** Constants such as calendar.SUNDAY and the setfirstweekday() method change which day each week begins on.
- ✅ **Iterate days:** The itermonthdays() method loops over a month and marks overlapping days from adjacent months as zeros.
- 🧪 **Helper functions:** Functions such as isleap(), weekday(), and monthrange() answer common date questions without any extra library.
- 🛠️ **Standard library:** The calendar module ships with Python, so it needs no installation before you import and use it.
- 🤖 **AI workflows:** Machine learning pipelines derive calendar features such as weekday and leap-year flags for time-series forecasting.

Read More

![Python Calendar Module](https://www.guru99.com/images/python-calendar.png)

The **calendar module in Python** has a calendar class that allows calculations for various tasks based on the date, month, and year. On top of that, the **TextCalendar** and **HTMLCalendar** classes in Python let you edit the calendar and use it as per your requirement. Let us see what we can do with the Python calendar.

## What is the calendar Module in Python?

The **calendar module** is part of the Python standard library, so it is available without any installation. It groups several classes and helper functions that build calendars and answer common date questions, such as which weekday a date falls on or how many days a month contains.

The module provides five main classes:

- **Calendar** is a base class that supplies the data the other calendars are built from.
- **TextCalendar** produces plain-text calendars for a month or a full year.
- **HTMLCalendar** produces calendars as HTML tables for web pages.
- **LocaleTextCalendar** is a text calendar that uses the day and month names of a chosen locale.
- **LocaleHTMLCalendar** is the HTML equivalent that respects a chosen locale.

By default, a calendar week begins on Monday, following the European convention. You can change the first day using a constant such as calendar.SUNDAY, as shown in the examples below.

## How to Print a Text Calendar in Python

**Step 1)** Run the code.

[![Print a text calendar in Python]()](https://www.guru99.com/images/Pythonnew/Python16.1.png)

- Code Line # 1: We begin with “import calendar”, which will import all the classes of this module.
- Code Line # 3: c= calendar.TextCalendar(calendar.SUNDAY) tells the interpreter to create a text calendar. The start of the month will be Sunday. In Python, you can format the calendar as you like and change the day the month begins with.
- Code Line # 4: str= c.formatmonth(2025,1) creates a calendar for the year 2025, Month 1 – January.
- Code Line # 5: print str will print the output.

Let us quickly change the value from Sunday to Thursday and check the output.

[![Change the first weekday of a Python calendar]()](https://www.guru99.com/images/Pythonnew/Python16.2.png)

## How to Print an HTML Calendar in Python

**Step 2)** You can also print the calendar in HTML format. This feature is helpful for developers who want to make changes to the look and feel of the calendar.

[![Print an HTML calendar in Python]()](https://www.guru99.com/images/Pythonnew/Python16.3.png)

## How to Loop Over the Days of a Month

**Step 3)** [Loops](https://www.guru99.com/if-loop-python-conditional-structures.html) over the days of a month by using c.itermonthdays (2025,4); it will fetch the total number of days for that month.

[![Loop over the days of a month in Python]()](https://www.guru99.com/images/Pythonnew/Python16.4.png)

- When you execute the code to get the total number of days for a specific month, say “April”, you will get 30 days in the output, but you will also see some zeros along with these days at the beginning and sometimes at the end.
- Zeros in the output mean that the day of the week is in an overlapping month, which means it does not belong to that month.
- These zeros appear in the output because, in your code, you have mentioned a day (Thursday). So when you call the function “c.itermonthdays”, it starts counting days from Thursday, and your Thursday may not start on the 1st of April – it might be the 28th or 29th of March. So the code starts counting days from the 28th of March and any days after that until the 1st of April. These days are counted as zeros, and in the output you will see these zeros. The same applies to the end of the month.
- So, except for the dates 1–30, all the dates from the previous as well as the following month appear in the output as zeros.

**Don't Miss:**

- [Python round() Function with EXAMPLES](https://www.guru99.com/round-function-python.html)
- [Python Queue: FIFO, LIFO Example](https://www.guru99.com/python-queue-example.html)
- [Python String format() Explain with EXAMPLES](https://www.guru99.com/python-string-format.html)
- [How to reverse a String in Python (5 Methods)](https://www.guru99.com/reverse-a-string-in-python.html)

## How to Fetch Month and Weekday Names From the Local System

**Step 4)** You can fetch data from the local system, such as months or weekdays.

[![Fetch month names from the local system in Python]()](https://www.guru99.com/images/Pythonnew/Python16.5.png)

- The output here shows that we have printed the month names from the local system. Likewise, you can also fetch the weekday names, as shown below.
- The output depends on the local system. If your local system is set to another country, it gives the output as per the local settings of that country. Here we have months, so it will not make a difference, but for a week or a day, it will certainly differ.

[![Fetch weekday names from the local system in Python]()](https://www.guru99.com/images/Pythonnew/Python16.6.png)

## How to Find a Specific Day for the Whole Year

**Step 5)** You can fetch the list of a specific day for a whole year. For example, there is an audit day on every first Monday of a week. Suppose you want to know the date of the first Monday for each month. You can use this code.

[![Find a specific day for the whole year in Python]()](https://www.guru99.com/images/Pythonnew/Python16.7.png)

- mycal = calendar.monthcalendar(2025, month) creates a calendar for the month.
- Set the variables week1 and week2 to the first and second week of the calendar.
- Check whether week 1 contains Monday and set the audit day.
- Otherwise, set the audit day as the first Monday in week 2.
- The output shows the date for the first Monday that falls in that month.
- The length of this Cal object depends on how many weeks there are in the month. In our case, it is one or two, as the first Monday of the week is in the first week most often, but if not, then we consider the second week. Let us see in detail why we also consider the second week.
- Here we are using the calendar constant Monday. The calendar object gives you constants that represent Sunday, Monday, Tuesday, and so on. If, in week one, the day represented by the Monday constant is not equal to 0 – remember, zeros mean days that belong to another month – then that Monday belongs to this month and the audit day is within week one. If it is 0, then the first Monday is not in the first week of the month, so it must be in the second.
- In that case, we set the audit day variable to the Monday represented by week two. The audit day comes back with whatever the day is for either the first or the second week.

## Complete Python Calendar Code Example

Here is the complete code.

**Python 2 Example**

```
import calendar
# Create a plain text calendar
c = calendar.TextCalendar(calendar.THURSDAY)
str = c.formatmonth(2025, 1, 0, 0)
print str

# Create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.THURSDAY)
str = hc.formatmonth(2025, 1)
print str
# loop over the days of a month
# zeroes indicate that the day of the week is in a next month or overlapping month
for i in c.itermonthdays(2025, 4):
    print i

    # The calendar can give info based on local such a names of days and months (full and abbreviated forms)
    for name in calendar.month_name:
        print name
    for day in calendar.day_name:
        print day
    # calculate days based on a rule: For instance an audit day on the second Monday of every month
    # Figure out what days that would be for each month, we can use the script as shown here
    for month in range(1, 13):
		# It retrieves a list of weeks that represent the month
        mycal = calendar.monthcalendar(2025, month)
		# The first MONDAY has to be within the first two weeks
        week1 = mycal[0]
        week2 = mycal[1]
        if week1[calendar.MONDAY] != 0:
            auditday = week1[calendar.MONDAY]
        else:
        # if the first MONDAY isn't in the first week, it must be in the second week
        	auditday = week2[calendar.MONDAY]
print "%10s %2d" % (calendar.month_name[month], auditday)

```

**Python 3 Example**

```
import calendar
# Create a plain text calendar
c = calendar.TextCalendar(calendar.THURSDAY)
str = c.formatmonth(2025, 1, 0, 0)
print(str)

# Create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.THURSDAY)
str = hc.formatmonth(2025, 1)
print(str)
# loop over the days of a month
# zeroes indicate that the day of the week is in a next month or overlapping month
for i in c.itermonthdays(2025, 4):
    print(i)

    # The calendar can give info based on local such a names of days and months (full and abbreviated forms)
    for name in calendar.month_name:
        print(name)
    for day in calendar.day_name:
        print(day)
    # calculate days based on a rule: For instance an audit day on the second Monday of every month
    # Figure out what days that would be for each month, we can use the script as shown here
    for month in range(1, 13):
		# It retrieves a list of weeks that represent the month
        mycal = calendar.monthcalendar(2025, month)
		# The first MONDAY has to be within the first two weeks
        week1 = mycal[0]
        week2 = mycal[1]
        if week1[calendar.MONDAY] != 0:
            auditday = week1[calendar.MONDAY]
        else:
        # if the first MONDAY isn't in the first week, it must be in the second week
        	auditday = week2[calendar.MONDAY]
print("%10s %2d" % (calendar.month_name[month], auditday))

```

## Useful Functions in the Python calendar Module

Besides the walkthrough above, the calendar module ships with several handy functions that work without creating a class instance:

- **calendar.calendar(year)** returns a full-year calendar as a multi-line string, while **calendar.prcal(year)** prints it directly.
- **calendar.month(year, month)** returns a single month as text, and **calendar.prmonth(year, month)** prints it.
- **calendar.monthcalendar(year, month)** returns the month as a list of week rows, where each day is an integer and days outside the month are 0.

These functions make quick, one-line calendar output possible, which is convenient in scripts and interactive sessions where you do not need the extra control of the TextCalendar or HTMLCalendar classes.

## How to Check for a Leap Year in Python

The calendar module can also tell you whether a year is a leap year, which matters because February has 29 days instead of 28 in such years. Two functions handle this:

- **calendar.isleap(year)** returns True when the year is a leap year and False otherwise.
- **calendar.leapdays(y1, y2)** returns the number of leap years in the range from y1 up to, but not including, y2.

For example, calendar.isleap(2024) returns True, while calendar.isleap(2025) returns False. Leap-year checks are useful whenever you validate dates, schedule recurring events, or count the exact number of days between two years.

## FAQs

🗓️ How is the calendar module different from the datetime module in Python?

The calendar module focuses on producing and analyzing calendars — text, HTML, weekday numbers, and leap-year checks. The datetime module handles specific timestamps, arithmetic, and formatting of individual dates and times. Many programs import both and use them together.

🔢 How do you get the weekday of a specific date using the calendar module?

Call calendar.weekday(year, month, day). It returns an integer from 0 (Monday) to 6 (Sunday). Pair it with calendar.day\_name to convert that number into a readable label such as Monday or Friday.

🧮 How do you get the number of days in a given month in Python?

Use calendar.monthrange(year, month). It returns a tuple whose second value is the day count, so calendar.monthrange(2025, 2)\[1] returns 28. The first value is the weekday of the first day of that month.

🌐 How do you display month and day names in another language in Python?

Use calendar.LocaleTextCalendar or calendar.LocaleHTMLCalendar and pass a locale such as “fr\_FR”. The formatted month then prints weekday and month names in that language, provided the locale is installed on the operating system.

💾 How do you save a Python HTML calendar to a file?

Generate the markup with HTMLCalendar().formatmonth(2025, 1), then open a file in write mode and call write() with that string. Saving it with a .html extension lets any browser display the styled calendar.

📆 Which day does the Python calendar module treat as the first day of the week?

By default the week starts on Monday, following the European convention. Call calendar.setfirstweekday(calendar.SUNDAY), or pass a constant such as calendar.SUNDAY to a TextCalendar, to make the week begin on another day.

📊 How is the Python calendar module used in data science or machine learning workflows?

Data pipelines use calendar functions to derive features such as weekday, week number, and leap-year flags from raw dates. These engineered calendar features help machine learning models capture weekly and seasonal patterns in time-series forecasting.

🤖 Can GitHub Copilot or agentic AI assistants generate Python calendar code?

Yes. GitHub Copilot and agentic AI assistants can write calendar module snippets — printing months, checking leap years, or building an HTML calendar — from a short comment. Review the output, since weekday indexing and first-day settings are easy to confuse.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/python-calendar.png","url":"https://www.guru99.com/images/python-calendar.png","width":"700","height":"250","caption":"Python CALENDAR","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/calendar-in-python.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/python","name":"Python"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/calendar-in-python.html","name":"Python calendar Module with Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/calendar-in-python.html#webpage","url":"https://www.guru99.com/calendar-in-python.html","name":"Python calendar Module with Example","dateModified":"2026-10-07T14:59:59+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/python-calendar.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/calendar-in-python.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/editorial","name":"Editorial Team","url":"https://www.guru99.com/author/editorial","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/favicon-new-logo.png","url":"https://www.guru99.com/images/favicon-new-logo.png","caption":"Editorial Team","inLanguage":"en-US"},"sameAs":["https://www.guru99.com/editorial-team"],"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Python","headline":"Python calendar Module with Example","description":"Calendar module in Python has the calendar class that allows the calculations based on date, month, and year. Learn how to print Text , HTML Calendar in python with examples.","keywords":"python","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/editorial","name":"Editorial Team"},"dateModified":"2026-10-07T14:59:59+05:30","image":{"@id":"https://www.guru99.com/images/python-calendar.png"},"copyrightYear":"2026","name":"Python calendar Module with Example","subjectOf":[{"@type":"HowTo","name":"How to Use Calendar module in Python","description":"Following are the steps to read a line-by-line from a given file using for-loop:","step":[{"@type":"HowToStep","name":"Run the code.","text":"Code Line # 1: We begin with 'import calendar' which will import all the classes of this module.","image":"https://www.guru99.com/images/Pythonnew/Python16.1.png","url":"https://www.guru99.com/calendar-in-python.html#step1"},{"@type":"HowToStep","name":"You can also print out the Calendar in HTML format,","text":"this feature is helpful for developer if they want to make any changes in the look and feel of calendar","image":"https://www.guru99.com/images/Pythonnew/Python16.3.png","url":"https://www.guru99.com/calendar-in-python.html#step2"},{"@type":"HowToStep","name":"Loops over the days of a month by using c.itermonthday (2025,4),","text":"it will fetch the total number of days for that month.","image":"https://www.guru99.com/images/Pythonnew/Python16.4.png","url":"https://www.guru99.com/calendar-in-python.html#step3"},{"@type":"HowToStep","name":"You can fetch the data from the local system,","text":"like months or weekdays, etc","image":"https://www.guru99.com/images/Pythonnew/Python16.5.png","url":"https://www.guru99.com/calendar-in-python.html#step4"},{"@type":"HowToStep","name":"You can fetch the list of the specific day for a whole year. For example, there is an audit day on every first Monday of a week. You want to know the date of first Monday for each month.","text":"You can use this code","image":"https://www.guru99.com/images/Pythonnew/Python16.7.png","url":"https://www.guru99.com/calendar-in-python.html#step5"}]},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"How is the calendar module different from the datetime module in Python?","acceptedAnswer":{"@type":"Answer","text":"The calendar module focuses on producing and analyzing calendars \u2014 text, HTML, weekday numbers, and leap-year checks. The datetime module handles specific timestamps, arithmetic, and formatting of individual dates and times. Many programs import both and use them together."}},{"@type":"Question","name":"How do you get the weekday of a specific date using the calendar module?","acceptedAnswer":{"@type":"Answer","text":"Call calendar.weekday(year, month, day). It returns an integer from 0 (Monday) to 6 (Sunday). Pair it with calendar.day_name to convert that number into a readable label such as Monday or Friday."}},{"@type":"Question","name":"How do you get the number of days in a given month in Python?","acceptedAnswer":{"@type":"Answer","text":"Use calendar.monthrange(year, month). It returns a tuple whose second value is the day count, so calendar.monthrange(2025, 2)[1] returns 28. The first value is the weekday of the first day of that month."}},{"@type":"Question","name":"How do you display month and day names in another language in Python?","acceptedAnswer":{"@type":"Answer","text":"Use calendar.LocaleTextCalendar or calendar.LocaleHTMLCalendar and pass a locale such as \"fr_FR\". The formatted month then prints weekday and month names in that language, provided the locale is installed on the operating system."}},{"@type":"Question","name":"How do you save a Python HTML calendar to a file?","acceptedAnswer":{"@type":"Answer","text":"Generate the markup with HTMLCalendar().formatmonth(2025, 1), then open a file in write mode and call write() with that string. Saving it with a .html extension lets any browser display the styled calendar."}},{"@type":"Question","name":"Which day does the Python calendar module treat as the first day of the week?","acceptedAnswer":{"@type":"Answer","text":"By default the week starts on Monday, following the European convention. Call calendar.setfirstweekday(calendar.SUNDAY), or pass a constant such as calendar.SUNDAY to a TextCalendar, to make the week begin on another day."}},{"@type":"Question","name":"How is the Python calendar module used in data science or machine learning workflows?","acceptedAnswer":{"@type":"Answer","text":"Data pipelines use calendar functions to derive features such as weekday, week number, and leap-year flags from raw dates. These engineered calendar features help machine learning models capture weekly and seasonal patterns in time-series forecasting."}},{"@type":"Question","name":"Can GitHub Copilot or agentic AI assistants generate Python calendar code?","acceptedAnswer":{"@type":"Answer","text":"Yes. GitHub Copilot and agentic AI assistants can write calendar module snippets \u2014 printing months, checking leap years, or building an HTML calendar \u2014 from a short comment. Review the output, since weekday indexing and first-day settings are easy to confuse."}}]}],"@id":"https://www.guru99.com/calendar-in-python.html#schema-510689","isPartOf":{"@id":"https://www.guru99.com/calendar-in-python.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/calendar-in-python.html#webpage"}}]}
```
