Well use a library called `calendar` which comes pre-installed in Python 3.x. If you don’t have it, just run this command on your terminal:
# Install the python-dateutil library using the pip command
pip install python-dateutil
# Import the calendar library from python-dateutil
from dateutil import calendar
# Create a variable named "year" and assign it the value of 2021
year=2021
# Create a variable named "cal" and assign it the value of the calendar for the specified year
cal=calendar.calendar(year)
# Print the calendar for the specified year
print(cal)
# Create a variable named "month" and assign it the value of 1
month=1
# Create a variable named "day" and assign it the value of 1
day=1
# Create a variable named "weekday" and assign it the value of the weekday for the specified date
weekday=calendar.weekday(year, month, day)
# Print the weekday for the specified date
print(weekday)
# Create a variable named "leap_year" and assign it the value of whether the specified year is a leap year or not
leap_year=calendar.isleap(year)
# Print whether the specified year is a leap year or not
print(leap_year)
This will download and install the package for us. Lets get started!
First of all, lets import our library `calendar`. We can do that by running this code in a Python file or in an IDE like PyCharm:
# Import the calendar library
import calendar
# Create a variable to store the current year
current_year = 2021
# Create a variable to store the current month
current_month = 9
# Use the calendar library to generate a calendar for the current month and year
# The calendar.month function takes in two arguments: the year and the month
# The result is stored in a variable called "cal"
cal = calendar.month(current_year, current_month)
# Print the calendar for the current month and year
print(cal)
# Output:
# September 2021
# 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
Now we have access to all its functions and classes. The first thing we want to do is print the current month using the `month_name()` function. This will return us the name of the current month as a string, for example “January”. Lets run this code:
# Import the calendar module
import calendar
# Use the month_name() function from the calendar module to get the name of the current month
current_month = calendar.month_name[1] # January
# Print the name of the current month
print(current_month)
This works because we passed 1 to the `month_name()` function which is the number that represents January (the first month of the year). If you want to print the current month, just run this code:
# Import the necessary modules
import calendar # Import the calendar module to access the month_name() function
from datetime import datetime # Import the datetime module to access the now() function
# Print the name of the current month
print(calendar.month_name(datetime.now().month)) # Call the month_name() function and pass in the current month number from the now() function, then print the result
# Output: January (if the current month is January)
# Explanation:
# The first line imports the necessary modules for the script to run.
# The second line uses the calendar module to access the month_name() function.
# The third line uses the datetime module to access the now() function, which returns the current date and time.
# The fourth line calls the month_name() function and passes in the current month number from the now() function.
# The fifth line prints the result, which is the name of the current month.
# The script will output the name of the current month, which will change depending on when the code is run.
Now lets see how we can customize our calendar using Python. Let’s say that you want to create a calendar for March 2019, but instead of printing all days, you only want to show weekends (Saturday and Sunday). We can do this by creating a function that will check if the day is Saturday or Sunday:
# Function to check if a given day is a weekend
def is_weekend(day):
# Convert the given day to a string in the format of "Weekday"
day_string = day.strftime("%A")
# Check if the day is either Sunday or Saturday
if day_string in ["Sunday", "Saturday"]:
# If it is, return True
return True
# If it is not, return False
return False
# Example usage
# Create a datetime object for March 1st, 2019
day = datetime.datetime(2019, 3, 1)
# Call the is_weekend function and pass in the day
is_weekend(day) # Returns False since March 1st, 2019 is a Friday
This function takes one argument `day`, which represents a datetime object, and returns True if it’s either Saturday or Sunday. Now lets create our calendar using the `monthcalendar()` function from the library we imported earlier:
import calendar # Importing the calendar library to use its functions
from datetime import date # Importing the date function from the datetime library
def print_customized_calendar(year, month): # Defining a function named print_customized_calendar that takes in two arguments, year and month
c = calendar.monthcalendar(year, month) # Using the monthcalendar function to get a list of lists representing the calendar for the given year and month
weekday = date(year, month, 1).weekday() # Using the weekday function to get the day of the week for the first day of the given month and year
for i, w in enumerate(calendar.month_name(month), start=3): # Using the enumerate function to iterate through the month names and start from the third index (Tuesday)
if i == 0: # Checking if the index is 0
print(f"{w} {year}") # Printing the month name and year
for j, day in enumerate(c[weekday:weekday+6]): # Using the enumerate function to iterate through the days of the week for the given month and year
if is_weekend(date(year, month, day)): # Checking if the day is a weekend by calling the is_weekend function
print(" " + str(day).rjust(2) + " ") # Adding spaces to align weekends with other days
else:
print(str(day).rjust(2), end="") # Printing the day with right justification
for _ in range(8-len(c[weekday:weekday+6])): # Using the range function to iterate through the remaining days of the week
print(" ", end="") # Printing spaces to align the remaining days with the rest of the calendar
if (i + 1) % 3 == 0: # Checking if the index plus one is divisible by three
print() # Printing a new line every three weeks
# Function to check if a given date is a weekend
def is_weekend(day):
if day.weekday() == 5 or day.weekday() == 6: # Checking if the day is either Saturday or Sunday
return True # Returning True if it is a weekend
else:
return False # Returning False if it is not a weekend
This function takes two arguments `year` and `month`, which represent the year and month we want to create a calendar for. Let’s run this code with an example:
# This function takes two arguments `year` and `month`, which represent the year and month we want to create a calendar for.
def print_customized_calendar(year, month):
# Create a list of weekdays to be used for printing the calendar
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
# Use the calendar module to get the number of days in the given month and year
num_days = calendar.monthrange(year, month)[1]
# Use the datetime module to get the first day of the given month and year
first_day = datetime.date(year, month, 1)
# Use the datetime module to get the weekday of the first day
first_weekday = first_day.weekday()
# Print the month and year as a header for the calendar
print(calendar.month_name[month], year)
# Print the weekdays as column headers for the calendar
print(' '.join(weekdays))
# Use a for loop to iterate through the days of the month
for day in range(1, num_days + 1):
# Use the datetime module to get the weekday of the current day
weekday = datetime.date(year, month, day).weekday()
# Check if the current day is a weekend (Saturday or Sunday)
if weekday == 5 or weekday == 6:
# Print the day with a space after it
print(day, end=' ')
else:
# Print a blank space to maintain the calendar format
print(' ', end=' ')
# Check if the current day is the last day of the week (Sunday)
if weekday == 6:
# Print a new line to start a new row in the calendar
print()
# Print a new line at the end of the calendar
print()
# Let's run this code with an example:
print_customized_calendar(2019, 3) # This will print a customized calendar for March 2019 showing only weekends
This function first gets the month calendar using `monthcalendar()`. Then it calculates the index of the first day of the month (which is a Monday if we start from Sunday). It then prints the name of the month and year, followed by each week’s days. If the day is Saturday or Sunday, it adds spaces to align them with other days. Finally, it prints new line every three weeks.
Thats all for this tutorial! I hope you enjoyed learning how to customize a calendar using Python. Let me know if you have any questions in the comments below!