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

    Criação de chatbot com API da OpenAI usando Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Python Chatbot with the OpenAI API

    Build a Python chatbot with the OpenAI Responses API, secure environment variables, conversation memory, model configuration, and practical error handling.

    Ler mais

    Tempo de leitura: 7 minutos
    10/07/2026
    Chatbot simples em Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Simple Chatbot with Python

    Build a simple Python chatbot with rules, input normalization, intents, random replies, JSON data, conversation loops, tests, and practical extension

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Criptografia e segurança de dados em Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Secure Password Generator in Python

    Build a secure password generator in Python with secrets, configurable character rules, a CLI, passphrases, validation, and practical tests.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Jogo da forca para iniciantes desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Hangman Game in Python

    Build a complete Hangman game in Python with random words, input validation, repeated-letter checks, lives, ASCII art, and replay support.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Quiz interativo no terminal desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Terminal Quiz Game in Python

    Build a terminal quiz game in Python with questions, input validation, scoring, shuffled answers, replay support, JSON loading, and tests.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Jogo de adivinhação de números desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Number Guessing Game in Python

    Build a number guessing game in Python with random numbers, input validation, hints, limited attempts, replay support, and clean functions.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026