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)
- The year is set to
2025
. - The week starts on Monday, following the ISO standard for week numbering.
Initializing the Week Number
week_number = 1
week_number
is initialized to1
, which helps in tracking calendar weeks (CW).
Looping Through Each Month (January to December)
for month in range(1, 13):
- The loop iterates 12 times (from
1
to12
), covering all months of the year.
Printing the Month Name and Headers
print(f"\n{calendar.month_name[month]}")
print("CW Mo Tu We Th Fr Sa Su")
- Prints the month name.
- Prints the weekdays header for clear formatting.
Generating the Month’s Calendar
month_cal = calendar.monthcalendar(year, month)
calendar.monthcalendar(year, month)
returns a list of weeks in the specified month.- Each week is represented as a list of 7 numbers, where:
0
represents days outside the current month.- Other numbers represent actual dates.
Processing Each Week in the Month
for week in month_cal:
- Iterates through each week of the month.
Generating Week Numbers & Days
week_with_cw = [f"CW{week_number:02d}"]
- Adds the current week number (e.g.,
CW01
,CW02
, etc.) in a two-digit format.
week_with_cw += [f"{day:2}" if day != 0 else " " for day in week]
- Iterates through each day in the week.
- If the day is not zero, it is added to the list.
- If the day is zero, it is replaced with a blank space (
" "
).
Printing the Week Data
print(" ".join(week_with_cw))
- Joins all elements of
week_with_cw
with spaces and prints the formatted week.
Incrementing the Week Number
week_number += 1
- Increments the
week_number
for the next iteration.
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.