Python设置工作起止时间后计算时间差仍包含非工作时间问题求助
解决方法
你遇到的问题核心是调用businessDuration时未传入定义好的starttime和endtime参数,导致函数使用默认规则计算,没有排除非工作时段。
问题根源
你的代码里虽然定义了starttime=(8,0,0)和endtime=(17,0,0),但调用businessDuration时只传递了时间节点、节假日列表和单位参数,遗漏了工作起止时间的配置,所以函数没有应用你设定的8-17点工作时间规则。
修改后的代码
# 把重复初始化逻辑提到循环外,减少资源消耗 holidaylist = pyholidays.Germany() starttime = (8, 0, 0) endtime = (17, 0, 0) unit = 'hour' ap = [] for index, row in df.iterrows(): first = row['New'] second = row['Assigned'] third = row['In Progress'] if pd.notnull(second): row['AP'] = businessDuration( first, second, holidaylist=holidaylist, starttime=starttime, # 新增工作起始时间参数 endtime=endtime, # 新增工作结束时间参数 unit=unit ) else: row['AP'] = businessDuration( first, third, holidaylist=holidaylist, starttime=starttime, # 新增工作起始时间参数 endtime=endtime, # 新增工作结束时间参数 unit=unit ) ap.append(row['AP'])
额外优化建议
如果你的DataFrame数据量较大,建议用apply替代iterrows提升运行效率,示例如下:
holidaylist = pyholidays.Germany() starttime = (8, 0, 0) endtime = (17, 0, 0) unit = 'hour' def calculate_ap(row): first = row['New'] second = row['Assigned'] third = row['In Progress'] if pd.notnull(second): return businessDuration(first, second, holidaylist=holidaylist, starttime=starttime, endtime=endtime, unit=unit) else: return businessDuration(first, third, holidaylist=holidaylist, starttime=starttime, endtime=endtime, unit=unit) df['AP'] = df.apply(calculate_ap, axis=1) ap = df['AP'].tolist()
内容的提问来源于stack exchange,提问作者dEV_21
相关产品推荐
相关产品推荐

