How to Create a Basic Calendar App in Python?
In this blog, we will learn how to build a simple calendar app using Python.
Method 1: Using the calendar Module
Python's standard library includes a handy module called calendar
that simplifies working with dates and calendars. We can utilize this module to create a basic calendar app. Below is a sample code snippet demonstrating how to display a calendar for a specific year and month:
import calendar
def display_calendar(year, month):
cal = calendar.month(year, month)
print(cal)
# Input year and month
year = int(input("Enter year: "))
month = int(input("Enter month: "))
# Display calendar
display_calendar(year, month)
Output:
Enter year: 2024
Enter month: 3
March 2024
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
In this method, we import the calendar
module and define a function display_calendar()
that takes the year and month as input parameters. Inside the function, we use the calendar.month()
function to generate a textual calendar for the specified year and month. Finally, we print the calendar to the console.
Method 2: Using the datetime Module
Another approach to creating a calendar app is by utilizing the datetime
module to work with dates and times. We can leverage the datetime
module to iterate over each day in a given month and display it in a calendar format.
import datetime
def display_calendar(year, month):
# Get the first day of the month
first_day = datetime.date(year, month, 1)
# Get the number of days in the month
num_days = calendar.monthrange(year, month)[1]
# Print the header
print(" " * 3 + calendar.month_name[month] + " " + str(year))
print("Mo Tu We Th Fr Sa Su")
# Initialize the starting day of the week
current_day = 1 - first_day.weekday()
# Loop through each week
while current_day <= num_days:
# Loop through each day in the week
for i in range(7):
if 1 <= current_day <= num_days:
print("{:2}".format(current_day), end=" ")
else:
print(" ", end=" ")
current_day += 1
print()
# Input year and month
year = int(input("Enter year: "))
month = int(input("Enter month: "))
# Display calendar
display_calendar(year, month)
Output:
Enter year: 2024
Enter month: 3
March 2024
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
In this method, we utilize the datetime
module to calculate the first day of the month and the total number of days in the month. Then, we iterate over each day in the month and print it in a calendar format, taking care of the alignment to ensure proper formatting.
Comments (0)