如何用Python获取下月及下下月的最后一个周四日期
获取指定月份的最后一个周四日期
你目前已实现获取当月最后一个周四的代码,如下:
import datetime dt = datetime.datetime.today() def lastThurs_currentmonth(dt): currDate, currMth, currYr = dt, dt.month, dt.year for i in range(31): if currDate.month == currMth and currDate.year == currYr and currDate.weekday() == 3: #print('dt:'+ str(currDate)) lastThuDate = currDate currDate += datetime.timedelta(1) return lastThurs_currentmonth(dt)
该代码输出示例:
datetime.datetime(2022, 11, 24, 11, 2, 17, 620842)
要获取下月和下下月的最后一个周四,可将原有函数改造为通用版本,支持传入月份偏移量(0代表当月,1代表下月,2代表下下月),优化后代码如下:
import datetime def get_last_thursday(base_date, month_offset=0): # 计算目标月份的年份和月份 target_year = base_date.year target_month = base_date.month + month_offset # 处理跨年情况,比如12月加1个月转为次年1月 while target_month > 12: target_year += 1 target_month -= 12 # 构造目标月份的第一天 first_day = datetime.datetime(target_year, target_month, 1) # 获取目标月份的最后一天 if target_month == 12: last_day = datetime.datetime(target_year + 1, 1, 1) - datetime.timedelta(days=1) else: last_day = datetime.datetime(target_year, target_month + 1, 1) - datetime.timedelta(days=1) # 从最后一天往前推算,找到最近的周四(weekday()返回3表示周四) days_to_backtrack = (last_day.weekday() - 3) % 7 last_thursday = last_day - datetime.timedelta(days=days_to_backtrack) # 清除时分秒,只保留日期部分 return last_thursday.replace(hour=0, minute=0, second=0, microsecond=0) # 测试调用 today = datetime.datetime.today() # 当月最后一个周四 current_last_thu = get_last_thursday(today) # 下月最后一个周四 next_month_last_thu = get_last_thursday(today, 1) # 下下月最后一个周四 next_next_month_last_thu = get_last_thursday(today, 2) print("当月最后一个周四日期:", current_last_thu) print("下月最后一个周四日期:", next_month_last_thu) print("下下月最后一个周四日期:", next_next_month_last_thu)
以2022年11月为例,运行后预期输出:
当月最后一个周四日期: datetime.datetime(2022, 11, 24, 0, 0) 下月最后一个周四日期: datetime.datetime(2022, 12, 29, 0, 0) 下下月最后一个周四日期: datetime.datetime(2023, 1, 26, 0, 0)
优化说明
- 直接计算目标月份的首尾日期,避免循环遍历31天的冗余操作,效率更高
- 自动处理跨年的月份计算,无需额外判断
- 可直接清除时分秒,输出纯净的日期型datetime对象,符合预期格式
参考内容:《使用Python获取当月最后一个周四》
内容的提问来源于stack exchange,提问作者Divyank
相关产品推荐
相关产品推荐

