Customize text calendar output with the TextCalendar class.
How It Works
calendar.TextCalendar(firstweekday=...) creates configurable text calendars. formatmonth() returns a string; prmonth() prints it. The firstweekday argument follows calendar weekday constants.
Step-by-Step Example
import calendar
text_calendar = calendar.TextCalendar(firstweekday=calendar.SUNDAY)
result = text_calendar.formatmonth(2026, 10)
print('October' in result)
print(result.splitlines()[1].strip().startswith('Su'))
Understanding the Example
- The expression 'calendar.TextCalendar(firstweekday=calendar.SUNDAY)' supplies the value stored as 'text_calendar'. This value is then used or checked by the later statements.
- The expression 'text_calendar.formatmonth(2026, 10)' supplies the value stored as 'result'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
True
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
For calculations use date and monthrange rather than parsing formatted text.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Confusing formatmonth() return values with prmonth() printing behavior.
- Create Monday-first and Sunday-first calendar views.
Key Takeaways
- Customize text calendar output with the TextCalendar class.
- calendar.TextCalendar(firstweekday=...) creates configurable text calendars.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.