如何使用Python的Calendar库高亮显示日历中的当日日期
Hey there! Highlighting today's date in Python's calendar output is totally doable—we just need to tweak the default formatting a bit. Let me walk you through a complete example with code, explanation, and what the end result looks like.
The core idea is to override the default date formatting logic in the calendar module. We'll use ANSI escape codes for terminal-based highlighting (works in most modern terminals like macOS Terminal, Linux shell, or Windows Terminal) or fall back to a text-based marker if your terminal doesn't support colors.
Example Code
import calendar from datetime import datetime # Grab today's date details today = datetime.today() current_year, current_month, current_day = today.year, today.month, today.day # ANSI escape codes for green background + black text (adjust as needed) HIGHLIGHT = '\033[42;30m' RESET = '\033[0m' # Custom calendar class to override date formatting class HighlightedCalendar(calendar.TextCalendar): def formatday(self, day, weekday, width): # Highlight today's date, else use default formatting if day == current_day: return f'{HIGHLIGHT}{day:^{width}}{RESET}' return super().formatday(day, weekday, width) # Initialize our custom calendar (use calendar.MONDAY if you want week to start on Monday) cal = HighlightedCalendar(calendar.SUNDAY) # Print the formatted calendar print(f"📅 {calendar.month_name[current_month]} {current_year}") print(cal.formatmonth(current_year, current_month, w=2, l=1))
How It Works
- We first fetch today's date using
datetime.today()to get the exact day/month/year we need to highlight. - The
HIGHLIGHTandRESETcodes tell the terminal to apply a green background (black text) and then revert to normal formatting after the date. You can swap these for other styles—for example,\033[33mgives yellow text if you prefer that. - By inheriting from
calendar.TextCalendarand overriding theformatdaymethod, we can inject our custom logic to highlight today's date while keeping all other default calendar formatting intact. - The
formatmonthmethod generates the full month calendar with our custom date styling.
Sample Output
In a terminal that supports ANSI codes, today's date will show up with a green background. If your terminal doesn't support colors, you can replace the ANSI codes with text markers like brackets:
HIGHLIGHT = '[' RESET = ']'
Which would produce output like this:
📅 October 2024 October 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
内容的提问来源于stack exchange,提问作者Zedx




