You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python calendar模块为指定日期(如节假日)添加自定义颜色?

给Python Calendar模块的日期添加自定义颜色的实现方案

嘿,这个问题我之前也碰到过!calendar.HTMLCalendar官方确实没直接提供给特定日期加颜色的API,但我们可以通过继承并重写它的核心方法来轻松实现需求,完全不需要额外复杂的依赖。

核心思路

HTMLCalendar的formatday方法负责生成每个日期对应的HTML元素,我们只需要创建一个它的子类,重写这个方法,在里面判断当前日期是否是目标节假日,然后给对应的HTML元素加上自定义样式就行。

完整代码示例

import calendar
from datetime import date

class ColoredHTMLCalendar(calendar.HTMLCalendar):
    def __init__(self, firstweekday=calendar.MONDAY, holidays=None):
        super().__init__(firstweekday)
        # 用集合存储节假日,格式为(year, month, day),方便快速查找
        self.holidays = holidays or set()

    def formatday(self, day, weekday):
        # 先调用父类方法获取默认的日期HTML
        default_html = super().formatday(day, weekday)
        # day为0代表是当月之外的日期,直接返回默认结果
        if day == 0:
            return default_html
        
        # 检查当前日期是否在节假日集合中
        current_date = (self.year, self.month, day)
        if current_date in self.holidays:
            # 替换默认HTML的内容,添加自定义样式(这里用红色加粗+浅红背景)
            return f'<td class="holiday">{day}</td>'
        return default_html

    def formatmonth(self, theyear, themonth, withyear=True):
        # 先获取父类生成的月份日历HTML
        month_html = super().formatmonth(theyear, themonth, withyear)
        # 自定义CSS样式,统一控制节假日的显示效果
        custom_css = """
        <style>
            table.calendar { border-collapse: collapse; }
            .calendar td, .calendar th { border: 1px solid #ddd; padding: 8px; text-align: center; }
            .holiday { color: #d32f2f; font-weight: bold; background-color: #ffebee; }
        </style>
        """
        # 生成完整的HTML页面,包含样式和日历内容
        return f'<html><head>{custom_css}</head><body>{month_html}</body></html>'

# 定义2020年9月的节假日(比如教师节9月10日)
september_holidays = {(2020, 9, 10)}

# 创建自定义日历实例,指定周日为一周的第一天
cal = ColoredHTMLCalendar(calendar.SUNDAY, september_holidays)
# 生成带样式的9月日历HTML
colored_calendar_html = cal.formatmonth(2020, 9)

# 将结果保存到HTML文件,直接打开就能看到效果
with open('september_2020_calendar.html', 'w', encoding='utf-8') as f:
    f.write(colored_calendar_html)

代码说明

  1. 子类继承:我们创建了ColoredHTMLCalendar继承自HTMLCalendar,这样可以复用父类的所有功能,只修改我们需要的部分。
  2. 节假日判断:在formatday里,我们检查当前日期是否在节假日集合中,如果是,就替换成带自定义样式的<td>标签。
  3. 样式优化:重写formatmonth方法添加自定义CSS,这样比内联样式更易维护,你可以根据自己的需求调整颜色、字体、背景等样式。
  4. 扩展方案:如果需要真实的节假日数据,可以用第三方库(比如chinesecalendar)来自动获取,示例代码如下:
    from chinese_calendar import is_holiday
    
    # 自动生成2020年9月的节假日集合
    september_holidays = set()
    for day in range(1, 31):
        current_date = date(2020, 9, day)
        if is_holiday(current_date):
            september_holidays.add((2020, 9, day))
    
    注意使用前需要先安装库:pip install chinesecalendar

其他扩展

除了formatday,你还可以重写formatweek、formatmonthname等方法,自定义日历的标题、整周样式等,灵活性非常高。

内容的提问来源于stack exchange,提问作者Akarii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:37:51