Site icon FSIBLOG

How To Print Calendar of Any Year with CW Using Python

How To Print Calendar of Any Year with CW Using Python

I am a Python enthusiast who enjoys building practical solutions. Today, I will walk you through a Python script that generates and prints a calendar for any year, displaying week numbers (CW) along with the days of the week. Additionally, we will improve its functionality by allowing user input, highlighting weekends, and saving the output to a text file for reference.

Explanation of the Code

This Python script generates a structured calendar view for a given year while incorporating week numbers (CW) and aligning the days correctly according to the ISO standard.

Importing the Calendar Module

import calendar

The calendar module is imported to work with dates and generate the calendar layout.

Setting the Year & Week Start Day

year = 2025
calendar.setfirstweekday(calendar.MONDAY)

Initializing the Week Number

week_number = 1

Looping Through Each Month (January to December)

for month in range(1, 13):

Printing the Month Name and Headers

print(f"\n{calendar.month_name[month]}")
print("CW  Mo Tu We Th Fr Sa Su")

Generating the Month’s Calendar

month_cal = calendar.monthcalendar(year, month)

Processing Each Week in the Month

for week in month_cal:

Generating Week Numbers & Days

week_with_cw = [f"CW{week_number:02d}"]
week_with_cw += [f"{day:2}" if day != 0 else "  " for day in week]

Printing the Week Data

print(" ".join(week_with_cw))

Incrementing the Week Number

week_number += 1

Enhancing the Functionality

To improve user experience, let’s add:

User input to select any year dynamically. Option to print only a specific month instead of the whole year. Highlighting of weekends (Saturday & Sunday) for better readability. Saving the calendar to a text file for reference.

Updated Code with More Features

import calendar

# User input for year
year = int(input("Enter the year: "))

# Set the first weekday (Monday as per ISO standard)
calendar.setfirstweekday(calendar.MONDAY)

# Initialize week number
week_number = 1

# Ask the user if they want the whole year or a specific month
print("\nOptions:")
print("1. Print entire year")
print("2. Print a specific month")
choice = int(input("Enter your choice (1 or 2): "))

if choice == 2:
    month = int(input("Enter the month number (1-12): "))
    months = [month]  # Convert single month input to a list
else:
    months = range(1, 13)  # Process all 12 months

# Open file to save output
with open("calendar_output.txt", "w") as file:
    for month in months:
        output = []
        output.append(f"\n{calendar.month_name[month]}")
        output.append("CW  Mo Tu We Th Fr Sa Su")
        month_cal = calendar.monthcalendar(year, month)
        
        for week in month_cal:
            week_with_cw = [f"CW{week_number:02d}"]
            
            for i, day in enumerate(week):
                if day != 0:
                    if i in [5, 6]:  # Highlight Saturdays and Sundays
                        week_with_cw.append(f"*{day:2}*")
                    else:
                        week_with_cw.append(f"{day:2}")
                else:
                    week_with_cw.append("  ")
            
            output.append(" ".join(week_with_cw))
            week_number += 1
        
        for line in output:
            print(line)
            file.write(line + "\n")

print("\nCalendar output saved to 'calendar_output.txt'")

New Features Added

User can enter any year dynamically.
Option to print either the full year or a specific month.
Weekends (Saturday & Sunday) are highlighted for better readability.
Calendar is saved in calendar_output.txt for reference.

Example Output (January 2025)

January
CW  Mo Tu We Th Fr Sa Su
CW01    1  2  3 * 4* * 5*
CW02    6  7  8  9 10 *11* *12*
CW03   13 14 15 16 17 *18* *19*
CW04   20 21 22 23 24 *25* *26*
CW05   27 28 29 30 31

Final Thoughts

This script provides an easy and efficient way to generate a calendar with week numbers for any given year. It enhances readability by highlighting weekends and allows users to save the output for reference. With the ability to select a specific month or the entire year, this script offers flexibility and practicality for various use cases.

Exit mobile version