Generator Public

Code #3400

Monthly Calendar Statistics

This Python script displays a table showing each month of a specified year, its total number of days, and the count of Saturdays within that month, correctly accounting for leap years.

Python
# display_monthly_stats.py

import calendar
import datetime

# --- Configuration ---
# Define the year for which to display the statistics.
# You can change this to any valid year.
TARGET_YEAR = 2024

# --- Main Logic ---
# Print a descriptive header for the output table.
print(f'--- Monthly Calendar Statistics for Year {TARGET_YEAR} ---\n')

# Define the header for the table columns.
# Using f-strings for alignment for better readability in the console.
print(f'{"Month":<15} {"Days":<10} {"Saturdays":<10}')
print('-' * 40) # Separator line for the header

# Create a Calendar instance to help with date calculations.
# By default, Monday is the first day of the week (0).
cal = calendar.Calendar(firstweekday=calendar.MONDAY)

# Iterate through each month of the year, from January (1) to December (12).
for month_num in range(1, 13):
    # Get the full name of the current month (e.g., 'January').
    month_name = calendar.month_name[month_num]
    
    # Get the number of days in the current month.
    # calendar.monthrange(year, month) returns a tuple: 
    # (weekday of first day, number of days in month).
    # We only need the second element (number of days).
    _, num_days = calendar.monthrange(TARGET_YEAR, month_num)
    
    # Initialize a counter for Saturdays in the current month.
    saturday_count = 0
    
    # Iterate through all days of the month using itermonthdays2.
    # itermonthdays2 yields (day_of_month, weekday_of_day) tuples.
    # day_of_month is 0 for days that are part of the padding from adjacent months.
    # weekday_of_day follows calendar conventions (0=Monday, ..., 5=Saturday, 6=Sunday).
    for day_of_month, weekday_of_day in cal.itermonthdays2(TARGET_YEAR, month_num):
        # Check if the day is a valid day of the current month (not padding) 
        # and if it is a Saturday (weekday 5).
        if day_of_month != 0 and weekday_of_day == calendar.SATURDAY:
            saturday_count += 1 # Increment the counter if it's a Saturday
            
    # Print the gathered statistics for the current month.
    print(f'{month_name:<15} {num_days:<10} {saturday_count:<10}')

# Print a footer to conclude the table.
print('-' * 40)
print('\nAnalysis complete.')
Prompt: displaying the months of the year with number of days and saturdays