Python Django中如何将HTMLCalendar的首周设为周日
修改Python日历周起始为周日的实现方案
要将你的自定义Calendar类的周起始从周一改为周日,有两种可靠的实现方式,优先推荐在类内部设置以避免影响全局:
方法一:在类初始化中设置(推荐)
直接在Calendar类的__init__方法中调用setfirstweekday方法,指定周日为周起始。这种方式只会影响当前日历实例,不会干扰其他使用calendar模块的代码。
修改后的__init__方法如下:
def __init__(self, year=None, month=None, group=None): self.year = year self.month = month self.group = group super(Calendar, self).__init__() # 设置周起始为周日 self.setfirstweekday(calendar.SUNDAY)
完整修改后的代码
import calendar from datetime import date from calendar import HTMLCalendar class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, group=None): self.year = year self.month = month self.group = group super(Calendar, self).__init__() # 添加此行设置周起始为周日 self.setfirstweekday(calendar.SUNDAY) def formatday(self, day): d = '' if day != 0: return f"<td name='date-event-input' id={date(year=self.year, month=self.month, day=day)}><span " \ f"class='date'>{day}</span><ul>{d}</ul></td>" return '<td></td>' def formatweek(self, theweek): week = '' for d, weekday in theweek: week += self.formatday(d) return f'<tr> {week} </tr>' def formatmonth(self, withyear=True): cal = f"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"calendar\" id=\"calendar-table-id\">\n" cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week)}\n' return cal
方法二:全局设置(不推荐)
如果你的项目中所有日历都需要以周日为起始,可以在代码开头全局设置:
import calendar calendar.setfirstweekday(calendar.SUNDAY)
但这种方式会影响所有使用calendar模块的功能,除非你确定全局都需要这个设置,否则不建议使用。
内容的提问来源于stack exchange,提问作者blueblob26
相关产品推荐
相关产品推荐

