如何用Python calendar模块显示带周数的日历?
如何用Python的calendar模块生成带周数的日历?
我需要显示带有周数的日历,Python的calendar模块用起来很方便,但找不到直接显示周数的方法。
现有执行命令:
python -m calendar --locale fr --encoding utf-8 --type text 2024
现有输出:
2024 janvier février mars Lu Ma Me Je Ve Sa Di Lu Ma Me Je Ve Sa Di Lu Ma Me Je Ve Sa Di 1 2 3 4 5 6 7 1 2 3 4 1 2 3 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 22 23 24 25 26 27 28 19 20 21 22 23 24 25 18 19 20 21 22 23 24 29 30 31 26 27 28 29 25 26 27 28 29 30 31
期望效果:
2024 janvier février mars Lu Ma Me Je Ve Sa Di Lu Ma Me Je Ve Sa Di Lu Ma Me Je Ve Sa Di 1 1 2 3 4 5 6 7 5 1 2 3 4 9 1 2 3 2 8 9 10 11 12 13 14 6 5 6 7 8 9 10 11 10 4 5 6 7 8 9 10 3 15 16 17 18 19 20 21 7 12 13 14 15 16 17 18 11 11 12 13 14 15 16 17 4 22 23 24 25 26 27 28 8 19 20 21 22 23 24 25 12 18 19 20 21 22 23 24 5 29 30 31 9 26 27 28 29 13 25 26 27 28 29 30 31
请问能否通过Python calendar模块实现该效果?若无法直接实现,如何扩展模块添加此功能?也可接受其他合理方案。
解决方案
1. 无法直接通过命令行工具实现
目前python -m calendar的命令行参数没有支持显示周数的选项,直接用命令行工具无法达成需求,但可以通过调用calendar模块的API扩展实现。
2. 基于calendar模块扩展实现
核心思路是利用calendar.Calendar类获取每月的日期与周数信息,再按照年度日历的三列排版规则拼接内容:
import calendar import locale # 设置法语本地化 locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8') def get_month_with_weeks(year, month): cal = calendar.Calendar(firstweekday=calendar.MONDAY) month_days = cal.monthdays2calendar(year, month) month_weeks = [] # 提取每周的ISO周数 for week in month_days: for day, _ in week: if day != 0: week_num = calendar.isocalendar(year, month, day)[1] month_weeks.append(week_num) break else: month_weeks.append(None) # 生成月份标题、星期表头 month_name = calendar.month_name[month] header = f" {month_name}" if month !=3 else f" {month_name}" week_days = " ".join(calendar.day_abbr[d] for d in range(calendar.MONDAY, calendar.SUNDAY+1)) week_header = f" {week_days}" # 生成带周数的日期行 lines = [] for idx, week in enumerate(month_days): week_num = month_weeks[idx] day_str = " ".join(f"{day:2d}" if day !=0 else " " for day, _ in week) week_str = f"{week_num:2d} " if week_num else " " lines.append(f"{week_str}{day_str}") return [header, week_header] + lines def generate_year_calendar_with_weeks(year): # 按三列分组月份 month_groups = [(1,2,3), (4,5,6), (7,8,9), (10,11,12)] year_header = f" {year}\n" output = [year_header] for group in month_groups: months_data = [get_month_with_weeks(year, m) for m in group] max_lines = max(len(m) for m in months_data) # 补全短月份的空行 for m in months_data: while len(m) < max_lines: m.append(" " * len(m[0])) # 拼接三列内容 for line_idx in range(max_lines): line_parts = [months_data[i][line_idx] for i in range(3)] output.append(" ".join(line_parts)) output.append("") return "\n".join(output) # 生成并打印2024年带周数的日历 print(generate_year_calendar_with_weeks(2024))
3. 第三方库替代方案
可以使用pyluach库(需先安装:pip install pyluach),它支持生成带周数的日历,核心逻辑和自定义扩展类似,都是基于日期计算周数后排版。
内容的提问来源于stack exchange,提问作者nico
相关产品推荐
相关产品推荐

