In this post, I will share a Python script to display a monthly calendar for any given year and month. The code uses Python’s built-in calendar module to generate the calendar in a readable format. The month() function from the calendar module is the core of this script. It takes two inputs—month and year—and returns a formatted calendar for the specified month and year.
In the provided code, you will need to input the month and year as command-line arguments. The script includes basic error handling to ensure the month is between 1 and 12. For the year, you can input any positive integer.
Here is the Python script:
import calendar
import sys
def generate_calendar(year, month):
"""
this function generates the calendar for a given month and year
"""
try:
print(calendar.month(year, month))
except IndexError:
print("invalid month. please enter a month between 1 and 12")
except Exception as e:
print(f"error: {e}")
def main():
"""
generate calendar for a given month and year
"""
# provide the month and year in mm-yyyy format (e.g. 01-2025)
args = sys.argv
# check if user provided a value or not
if len(args) < 2:
print("please provide month and year in mm-yyyy format")
else:
vals = args[1]
try:
mm, yyyy = int(vals.split('-')[0]), int(vals.split('-')[1])
except ValueError:
print("invalid input. please provide month and year in mm-yyyy format (e.g. 12-2024)")
# generate calender for the given month and year
generate_calendar(yyyy, mm)
if __name__ == "__main__":
main()
Save the script with the filename calendar_generator.py (or any other name you prefer). Run the script from the terminal as shown below:
python calendar_generator.py 01-2025
Here is the output of the code:
January 2025
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Please let me know in the comments if you find any errors in the code.