Displaying Calendars with LocaleTextCalendar and LocaleHTMLCalendar

But not just any old boring calendar, oh no. We’re talking about fancy calendars with locale support using Python’s built-in `calendar` module.

To start, let’s import the necessary modules:

# Import the necessary modules
import calendar # Importing the calendar module to work with calendars
from datetime import date # Importing the date class from the datetime module to work with dates

# Create a function to print a fancy calendar with locale support
def print_fancy_calendar(year, month, locale=None):
    """
    This function prints a fancy calendar for a given year and month, with optional locale support.
    :param year: The year for which the calendar is to be printed
    :param month: The month for which the calendar is to be printed
    :param locale: Optional parameter for locale support, defaults to None
    """
    # Create a new calendar object
    fancy_calendar = calendar.LocaleTextCalendar(locale)

    # Get the current date
    today = date.today()

    # Print the month and year header
    print(fancy_calendar.formatmonthname(year, month))

    # Print the days of the week header
    print(fancy_calendar.formatweekheader())

    # Print the calendar for the given month and year
    for week in fancy_calendar.monthdayscalendar(year, month):
        for day in week:
            # Check if the day is in the current month
            if day == 0:
                # Print an empty space for days not in the current month
                print(" ", end=" ")
            else:
                # Print the day with a leading zero if necessary
                print(f"{day:2d}", end=" ")
        print()

    # Print a message if the current date is in the given month and year
    if today.year == year and today.month == month:
        print("Today is", today.day)

# Call the function to print a fancy calendar for the current month and year
print_fancy_calendar(today.year, today.month)

Now that we have our tools ready to go, let’s create a function to display a simple text calendar using Python’s built-in `calendar` module. This is perfect for when you need a quick and dirty way to see what days are in which month:

# Function to print a simple text calendar for a given year and month
def print_text_calendar(year, month):
    # Use the built-in calendar module to generate a calendar for the given year and month
    cal = calendar.monthcalendar(year, month)
    # Create a header string using the month name and year
    header = f"{calendar.month_name[month]} {year}"
    # Loop through each week in the calendar
    for week in cal:
        # Create a string for each week, with each day right-justified and padded with spaces
        line = " ".join([str(day).rjust(2) if day != 0 else '   ' for day in week])
        # Print the header and a line of dashes to separate it from the calendar
        print(f"{header}\n{'-' * len(line)}")
        # Print the string for the current week
        print(line)

This function takes two arguments `year` and `month`. It uses Python’s built-in `calendar.monthcalendar()` to generate a list of days for the given month, then formats it into a string with some padding so that each day is aligned nicely in the output. The header at the top shows the name of the month and year.

Now locale support. If you want your calendar to display month and weekday names in a language other than English (or if you just prefer using unicode), Python has got you covered with its `calendar` module. Here’s an example function that uses the `LocaleHTMLCalendar` class:

# Import necessary modules
from datetime import date, timedelta
import locale

# Set French as our default locale
locale.setlocale(locale.LC_ALL, 'fr_FR')

# Define function to print HTML calendar
def print_html_calendar(year, month):
    # Use Sunday as the first day of the week (0 is Monday in Python's `calendar` module)
    cal = calendar.LocaleHTMLCalendar(firstweekday=6)
    # Set our locale to French
    cal.localize(locale('fr'))
    # Loop through each week in the month
    for weeknum, weeks in enumerate(cal.month_days_table[year][month]):
        # Skip empty weeks
        if not weeks:
            continue
        # Create header for the month and year
        header = f"{calendar.month_name[month]} {year}"
        # Print header in HTML format
        print(f'<h2>{header}</h2>')
        # Loop through each day in the week
        for week in weeks:
            # Create a row for each day
            row = '<tr>'
            # Skip empty days
            if not day:
                continue
            # Determine if day is even or odd and assign appropriate class
            class_str = 'even' if (weeknum * 7 + week.index(day) % 7) % 2 == 0 else 'odd'
            # Add day to row with appropriate class
            row += f'<td class="{class_str}">{day}</td>'
            # Print row in HTML format
            print(row + '</tr>')
        # Add line break after each week
        print('<br/>')

This function uses the `LocaleHTMLCalendar` class to generate an HTML table with month and weekday names in French. The `setlocale()` function is used to set our default locale, which will be used by the calendar module for formatting dates and strings. Note that we’re using a timedelta object to calculate the number of weeks between two given dates (in this case, the first day of the month).

With just a few lines of code, you can display fancy calendars with locale support in Python.

SICORPS