The calendar
module in Python isn’t limited to displaying month and year calendars; it also offers advanced functionalities to customize and manipulate calendar data. In this blog, we’ll dive into some advanced features and how to implement them in Python.
1. Customizing the First Day of the Week
By default, the calendar
module considers Monday as the first day of the week. You can change this to any other day, such as Sunday.
Code Example:
import calendar
# Set Sunday as the first day of the week
calendar.setfirstweekday(calendar.SUNDAY)
# Display the calendar for December 2024
print(calendar.month(2024, 12))
Output:
December 2024
Su Mo Tu We Th Fr Sa
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
2. Highlighting Specific Dates
If you need to mark specific dates (e.g., holidays or events), you can overlay these dates on a generated calendar. Let’s create a custom function for this.
Code Example:
import calendar
def highlight_dates(year, month, highlights):
cal = calendar.TextCalendar()
month_calendar = cal.formatmonth(year, month).split("\n")
# Highlight specified dates
for i, line in enumerate(month_calendar):
for day in highlights:
if f"{day:2}" in line: # Match the day with padding
month_calendar[i] = line.replace(f"{day:2}", f"[{day:2}]")
return "\n".join(month_calendar)
# Example usage
year = 2024
month = 12
highlights = [25, 31] # Christmas and New Year's Eve
print(highlight_dates(year, month, highlights))
Output:
December 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]
3. Generate a Calendar in HTML
The HTMLCalendar
class generates calendars in HTML format, which is useful for web applications.
Code Example:
from calendar import HTMLCalendar
# Create an HTMLCalendar object
cal = HTMLCalendar()
# Generate HTML for December 2024
html_calendar = cal.formatmonth(2024, 12)
# Save the HTML to a file
with open("calendar.html", "w") as file:
file.write(html_calendar)
print("HTML calendar generated successfully!")
Output Preview:
When you open calendar.html
in a browser, it will display the calendar styled in HTML.
4. Finding Leap Years
You can easily check if a given year is a leap year using calendar.isleap()
.
Code Example:
import calendar
# Check if a year is a leap year
year = 2024
if calendar.isleap(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Output:
2024 is a leap year.
5. Calculating the Number of Leap Years
You can count the number of leap years in a range using calendar.leapdays()
.
Code Example:
import calendar
# Count leap years between two years
start_year = 2000
end_year = 2024
leap_years = calendar.leapdays(start_year, end_year + 1) # Include end_year
print(f"There are {leap_years} leap years between {start_year} and {end_year}.")
Output:
There are 7 leap years between 2000 and 2024.
6. Get Day of the Week
You can find the day of the week for any date using calendar.weekday()
.
Code Example:
import calendar
# Get the day of the week for a specific date
year = 2024
month = 12
day = 25
weekday = calendar.weekday(year, month, day)
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print(f"{year}-{month}-{day} falls on a {days[weekday]}.")
Output:
2024-12-25 falls on a Wednesday.
7. Create a Yearly Calendar
You can generate a full calendar for a year with formatyear()
.
Code Example:
import calendar
# Generate a text calendar for the year 2024
year = 2024
cal = calendar.TextCalendar()
print(cal.formatyear(year, 2, 1, 1, 3)) # Custom spacing
Output:
2024
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7 1 2 3 4 1 2
8 9 10 11 12 13 14 5 6 7 8 9 10 11 4 5 6 7 8 9 10
15 16 17 18 19 20 21 12 13 14 15 16 17 18 11 12 13 14 15 16 17
...
8. Creating a Custom Calendar Class
You can subclass calendar.TextCalendar
to build your own custom calendars with added functionalities.
Code Example:
import calendar
class CustomCalendar(calendar.TextCalendar):
def formatmonth(self, year, month, with_year=True):
result = super().formatmonth(year, month, with_year)
return result.upper() # Convert the calendar to uppercase
# Example usage
custom_cal = CustomCalendar()
print(custom_cal.formatmonth(2024, 12))
Output:
DECEMBER 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
Conclusion
The calendar
module in Python is versatile, offering functionalities from basic calendar display to advanced customizations like highlighting dates, generating HTML calendars, and calculating leap years. These features can be integrated into scheduling systems, event management tools, and other calendar-based applications.
Would you like to explore a specific feature or integrate these functionalities into a project? Let me know!
- Python Program to Find Substring in a String
- Here’s a simple Snake game implemented in Python using the pygame library. You can run this code to play a classic version of the game.
- Concatenate Two Strings in Python
- How to Find the Length of a String in Python: A Beginner’s Guide
- Convert a String to Lowercase in Python