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

求助:Python中无需自定义类的工作时长计算实现方案

解决Python计算工作时长的问题

你使用的BusinessHours并非Python标准库自带工具,属于第三方库python-businesshours,首先需要完成安装:

pip install businesshours

你的代码存在两个核心问题,导致无法得到预期结果:

  • 周末参数错误:Python的datetime.datetime.weekday()返回值范围是0(周一)到6(周日),不存在7这个值。如果周末是周六和周日,应设置weekends=[5,6](5对应周六,6对应周日)。
  • 工作时长参数与预期不匹配:你期望输入2019-12-01 09:30:00到2019-12-07 12:15:00输出40小时,但按worktiming=[9,18](每天9小时工作时长)计算,工作日为12月2日-12月6日共5天,总时长应为45小时。若要得到40小时,需将每日工作时长改为8小时,即设置worktiming=[9,17]。

修正后的代码示例

import datetime
from businesshours import BusinessHours

# 预期输入的起止时间
start_time = datetime.datetime(2019, 12, 1, 9, 30, 0)
end_time = datetime.datetime(2019, 12, 7, 12, 15, 0)

# 修正周末参数,设置每日工作时间为9:00-17:00
hours = BusinessHours(start_time, end_time, worktiming=[9, 17], weekends=[5, 6], holidayfile=None)
print(hours.gethours())  # 输出40.0

不依赖businesshours的替代方案

如果不想使用上述第三方库,可以借助更常用的python-dateutil库实现,无需自定义类:

pip install python-dateutil
import datetime
from dateutil.rrule import rrule, DAILY
from dateutil.parser import parse

def calculate_work_hours(start_str, end_str, work_start=9, work_end=17, weekends=[5,6]):
    start = parse(start_str)
    end = parse(end_str)
    total_seconds = 0

    # 遍历所有日期,筛选工作日计算有效时长
    for dt in rrule(DAILY, dtstart=start.date(), until=end.date()):
        if dt.weekday() in weekends:
            continue
        # 构建当天的工作起止时间
        work_start_dt = datetime.datetime.combine(dt.date(), datetime.time(work_start))
        work_end_dt = datetime.datetime.combine(dt.date(), datetime.time(work_end))
        # 计算当天实际贡献的时长
        period_start = max(start, work_start_dt)
        period_end = min(end, work_end_dt)
        if period_start < period_end:
            total_seconds += (period_end - period_start).total_seconds()
    
    return total_seconds / 3600

# 测试预期输入
print(calculate_work_hours("2019-12-01 09:30:00", "2019-12-07 12:15:00"))  # 输出40.0

内容的提问来源于stack exchange,提问作者user14269252

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:10:29