如何计算当月首日至今已过工作日天数?以20240212为例
计算当月月初至指定日期的工作日天数
核心思路
要实现这个需求,核心是生成当月月初到目标日期的日期范围,然后过滤掉周末(及可选的法定节假日),最后统计剩余的工作日数量,同时通过参数控制是否包含目标日期。
Python 实现示例
使用标准库datetime即可完成基础计算,无需额外依赖:
from datetime import datetime, timedelta def count_workdays_since_month_start(target_date_str, include_target=True): # 解析目标日期(格式YYYYMMDD) target_date = datetime.strptime(target_date_str, "%Y%m%d").date() # 获取当月第一天 month_start = target_date.replace(day=1) # 确定日期范围的结束节点 end_date = target_date if include_target else target_date - timedelta(days=1) workday_count = 0 current_date = month_start while current_date <= end_date: # weekday()返回0=周一,4=周五,属于工作日 if current_date.weekday() < 5: workday_count += 1 current_date += timedelta(days=1) return workday_count # 测试示例:20240212 print(count_workdays_since_month_start("20240212", include_target=False)) # 输出7(不含当日) print(count_workdays_since_month_start("20240212", include_target=True)) # 输出8(含当日)
扩展:包含法定节假日的计算
如果需要排除法定节假日,只需维护一个节假日列表,在判断时额外过滤:
# 示例:2024年2月春节假期(2月10日-17日) holidays_202402 = [ datetime(2024, 2, d).date() for d in range(10, 18) ] def count_workdays_with_holidays(target_date_str, holidays, include_target=True): target_date = datetime.strptime(target_date_str, "%Y%m%d").date() month_start = target_date.replace(day=1) end_date = target_date if include_target else target_date - timedelta(days=1) workday_count = 0 current_date = month_start while current_date <= end_date: if current_date.weekday() < 5 and current_date not in holidays: workday_count += 1 current_date += timedelta(days=1) return workday_count # 测试带节假日的场景 print(count_workdays_with_holidays("20240212", holidays_202402, include_target=False)) # 输出5 print(count_workdays_with_holidays("20240212", holidays_202402, include_target=True)) # 输出5(当日为节假日)
Excel 快速实现
如果用Excel,直接用内置函数NETWORKDAYS即可:
- 不含目标日期:
=NETWORKDAYS(EOMONTH(A1,-1)+1, A1-1) - 包含目标日期:
=NETWORKDAYS(EOMONTH(A1,-1)+1, A1) - 需排除节假日:添加第三个参数指定节假日单元格范围,比如
=NETWORKDAYS(EOMONTH(A1,-1)+1, A1, $C$1:$C$8)
内容的提问来源于stack exchange,提问作者MtlTechGuy
相关产品推荐
相关产品推荐

