You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pandas如何生成仅包含指定周几的日期序列实现自定义工作日任务排期

自定义指定周几的pandas工作日序列计算方案

核心思路:使用pandas内置的CustomBusinessDay偏移量替代默认的BDay,通过weekmask参数指定需要保留的有效工作日,无需修改原有工期计算的核心逻辑,仅调整日期偏移部分即可。


实现步骤

1. 定义自定义工作日规则

首先导入CustomBusinessDay,通过weekmask指定有效工作日:

import numpy as np
import pandas as pd
from pandas.tseries.offsets import CustomBusinessDay

# weekmask参数说明:多个工作日用空格分隔,对应缩写如下
# 周一=Mon、周二=Tue、周三=Wed、周四=Thu、周五=Fri、周六=Sat、周日=Sun
# 示例:仅保留周三、周四作为有效工作日
custom_workday = CustomBusinessDay(weekmask="Wed Thu")

2. 替换原有代码中的日期偏移逻辑

将你原有代码最后两行的BDay替换为上面定义的custom_workday即可:

# 原有核心逻辑保持不变
durations = [4, 8, 2, 16, 5]
hours_per_day = 7
start_date = "2021-07-01"

arr = np.array(durations)
bins = [0]
bins.extend([x[-1] for x in np.array_split(np.arange(np.sum(arr)), np.ceil(np.sum(arr)/hours_per_day))])
totals = np.cumsum(arr)
idx = np.digitize(totals, bins, right=True)-1
start_deltas = np.pad(idx, (1, 0))[:-1]

df = pd.DataFrame({"task":[f"task{x}" for x in range(len(durations))],
                   "duration": durations,
                   "delta":start_deltas})
df["start_date"] = pd.to_datetime(start_date)

# 仅修改这两行的BDay为自定义的custom_workday
df["start_date"] = df.apply(lambda x: x["start_date"] + custom_workday * pd.to_timedelta(x["delta"], "d").days, axis=1)
df["end_date"] = df.apply(lambda x: x["start_date"] + custom_workday * (x["duration"]//hours_per_day), axis=1)

效果验证示例

# 2021-07-01为周四,按周三、周四有效规则测试
start = pd.to_datetime("2021-07-01")
print(start + custom_workday * 1) 
# 输出:2021-07-07 00:00:00(下周三,符合仅周三、周四计数的规则)

内容的提问来源于stack exchange,提问作者Анатолий Григорович

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 05:54:03