Python教程112:找到每月的第三个星期五(calendar)
为了获取每月的第三个星期五,可以使用Python的calendar模块来生成月份的周历,并从中提取所需的星期五日期。
1.指定月份的星期五
步骤解析:
导入模块:使用calendar生成月份周历,datetime.date构造日期对象。
生成周历:calendar.monthcalendar(year, month)返回一个二维列表,每周为一个子列表,包含从周一到周日的日期(不属于该月的日期用0填充)。
提取星期五日期:遍历每周,获取每个周五的日期(索引为calendar.FRIDAY,即4),并过滤掉0值。
返回第三个星期五:从提取的星期五列表中取第三个元素(索引2)构造日期对象。
import calendar
from datetime import datedef get_third_friday(year, month):cal = calendar.monthcalendar(year, month)print('1.生成指定月份日历'.center(30, '-'))print(cal)fridays = [week[calendar.FRIDAY] for week in cal if week[calendar.FRIDAY] != 0]print('2.本月的星期五'.center(30, '-'))print(fridays)print('3.获取2025年5月的第三个星期五'.center(30, '-'))return date(year, month, fridays[2])print(get_third_friday(2025, 5))
输出内容:
----------1.生成指定月份日历----------
[[0, 0, 0, 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, 0]]
-----------2.本月的星期五-----------
[2, 9, 16, 23, 30]
------3.获取2025年5月的第三个星期五------
2025-05-16
2.某年2025每个月所有的第三个星期五日期
# -*- coding: utf-8 -*-
# @Author : 小红牛
# 微信公众号:WdPython
import calendar
from datetime import datedef get_third_friday(year, month):cal = calendar.monthcalendar(year, month)fridays = [week[calendar.FRIDAY] for week in cal if week[calendar.FRIDAY] != 0]return date(year, month, fridays[2])# 1.获取2025年所有月份的第三个星期五
third_fridays_2025 = []
for month in range(1, 13):third_friday = get_third_friday(2025, month)third_fridays_2025.append(third_friday)# 2.打印结果(按月份格式化)
for idx, day in enumerate(third_fridays_2025, start=1):print(f"2025-{idx:02d} 的第三个星期五:{day.strftime('%Y-%m-%d')}")
输出内容
2025-01 的第三个星期五:2025-01-17
2025-02 的第三个星期五:2025-02-21
2025-03 的第三个星期五:2025-03-21
2025-04 的第三个星期五:2025-04-18
2025-05 的第三个星期五:2025-05-16
2025-06 的第三个星期五:2025-06-20
2025-07 的第三个星期五:2025-07-18
2025-08 的第三个星期五:2025-08-15
2025-09 的第三个星期五:2025-09-19
2025-10 的第三个星期五:2025-10-17
2025-11 的第三个星期五:2025-11-21
2025-12 的第三个星期五:2025-12-19
完毕!!感谢您的收看
----------★★跳转到历史博文集合★★----------
我的零基础Python教程,Python入门篇 进阶篇 视频教程 Py安装py项目 Python模块 Python爬虫 Json Xpath 正则表达式 Selenium Etree CssGui程序开发 Tkinter Pyqt5 列表元组字典数据可视化 matplotlib 词云图 Pyecharts 海龟画图 Pandas Bug处理 电脑小知识office自动化办公 编程工具 NumPy Pygame