Generate a Monthly Calendar in Python in 2 Minutes

Published on: May 29, 2026
Reading time: 4 minutes
Calendário mensal gerado automaticamente com Python

Did you know that creating a complete, formatted calendar can be done in just a few lines of code? When organizing projects or planning tasks, a quick view of dates and weekdays is often needed. Learning how to generate a monthly calendar in Python is one of the most efficient ways to understand how the language handles its standard library to simplify a developer’s daily work. This guide explores the calendar module, a native tool that eliminates the need for complex manual calculations around leap years or which weekday a particular date falls on.

Why use Python to generate calendars?

Python is widely known for its “batteries included” philosophy, meaning that after installing Python, you already receive a robust set of ready-to-use tools. The calendar module is one of those hidden gems. With it, you do not need to worry about whether February has 28 or 29 days, or what the first day of January 1990 was.

Beyond convenience, Python automation lets you integrate these calendars into larger systems. Imagine a script that automatically generates monthly reports or a bot that organizes appointments. Mastering how to generate a monthly calendar in Python opens the door to building custom productivity tools, including ones built on task automation with Python.

The calendar module: the foundation

Unlike other tasks that require installing Python libraries via package managers, calendar generation uses a built-in module. This keeps your code portable and fast. The calendar module provides classes and functions for working with dates focused on displaying them as matrices or formatted strings.

Step 1: Importing the module

import calendar

Step 2: Defining the year and month

year = 2024
month = 10  # October

Step 3: Generating and displaying the result

print(calendar.month(year, month))

The month function receives the year and month as arguments and returns a formatted string ready to be printed to the screen.

Custom formatting: changing the first day of the week

Python’s default first weekday is Monday (index 0). To start on Sunday (index 6), use setfirstweekday. This small change reshapes the entire grid so days fall under the correct columns.

import calendar

# Set Sunday as the first day of the week
calendar.setfirstweekday(calendar.SUNDAY)

year = 2024
month = 12
print(calendar.month(year, month))

Adding user input

A useful script should be interactive. Instead of hardcoding the year and month, ask the user what period they want to view. The values must be converted to Python integers for the comparison to work.

yy = int(input("Enter the year (e.g. 2024): "))
mm = int(input("Enter the month (1-12): "))

print("n" + calendar.month(yy, mm))

Saving the calendar to a text file

To save the calendar for later use, write the generated string to a file using the context manager pattern.

import calendar

year = 2025
month = 1
content = calendar.month(year, month)

with open("calendar.txt", "w") as file:
    file.write(content)

print("Calendar saved successfully to calendar.txt!")

Complete project script

import calendar

def generate_calendar():
    print("--- Quick Monthly Calendar Generator ---")

    # Set Sunday as the first day of the week
    calendar.setfirstweekday(calendar.SUNDAY)

    try:
        year = int(input("Enter the desired year: "))
        month = int(input("Enter the month number (1 to 12): "))

        if 1 <= month <= 12:
            cal_text = calendar.month(year, month)
            print("nResult:")
            print(cal_text)
        else:
            print("Error: Month must be between 1 and 12.")

    except ValueError:
        print("Error: Please enter valid integer numbers only.")

if __name__ == "__main__":
    generate_calendar()

Other useful functions in the calendar module

Beyond generating a monthly view, the module offers several functions useful in programming logic. calendar.isleap(year) returns True if the year is a leap year. calendar.weekday(year, month, day) returns the weekday as an integer from 0 to 6. calendar.monthrange(year, month) returns a tuple with the weekday of the first day of the month and the total number of days in it. And calendar.calendar(year) prints all 12 months in a multi-column layout for full-year planning.

Full technical details are available in the official Python calendar module documentation. For validating your date logic against international standards, Time and Date is an excellent reference.

Frequently Asked Questions

Can I generate a calendar in HTML with Python?

Yes. The library provides calendar.HTMLCalendar, which automatically generates a table formatted in HTML tags, ready to be embedded in websites.

How do I find out how many days a specific month has?

Use calendar.monthrange(year, month)[1]. The second element of the returned tuple is exactly the number of days in that month.

Does Python handle leap years automatically?

Yes. The calendar module has the Gregorian calendar logic built in, handling leap years correctly without you needing to code the exception rules yourself.

How do I start the week on Monday instead of Sunday?

Monday is actually Python's default. To make it explicit, use calendar.setfirstweekday(calendar.MONDAY).

Where is calendar generation code useful in practice?

It is commonly used in system logs, timesheet generators, scheduling bots, and office automation scripts that need to reference dates visually.

Does this code work on any Python version?

The module has been available since early versions. Python 3.x is recommended for better character compatibility and access to newer methods.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Conversor de moedas desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Python Currency Converter Step by Step

    Build a Python currency converter step by step using the requests library and a real exchange rate API, with user

    Ler mais

    Tempo de leitura: 4 minutos
    29/05/2026
    Sistema de login simples desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Simple Python Login System with TXT Files

    Learn how to build a simple Python login system using TXT files, with user registration, password validation, error handling, and

    Ler mais

    Tempo de leitura: 5 minutos
    29/05/2026
    Sistema de lembretes e alarmes desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build an Alarm Reminder System in Python

    Learn how to build a Python alarm reminder system step by step, using datetime, playsound, input validation, and a complete

    Ler mais

    Tempo de leitura: 5 minutos
    29/05/2026
    Sistema de tradução automática desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build an Automatic Translation System in Python

    Learn how to build an automatic translation system in Python using Googletrans, with language detection, batch translation, error handling, and

    Ler mais

    Tempo de leitura: 5 minutos
    28/05/2026
    Landing page simples criada com Python e Tailwind CSS
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Python Landing Page with Tailwind CSS

    Learn how to build a modern landing page with Python, Flask, Tailwind CSS, responsive design, forms, project structure, and deployment

    Ler mais

    Tempo de leitura: 8 minutos
    19/05/2026
    Conversão de áudio para texto usando Python gratuitamente
    Projects
    Foto de perfil de Leandro Hirt da Academify

    How to Convert Audio to Text with Python for Free

    Learn how to convert audio to text with Python for free using SpeechRecognition and Whisper. This guide covers WAV and

    Ler mais

    Tempo de leitura: 9 minutos
    12/05/2026