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

如何用Pandas计算时间戳小时差且排除周末时长

你可以通过新增一个扣除周末计算有效时长的辅助函数,替换原有直接计算时间差的逻辑实现需求,修改后的完整代码如下:

import pandas as pd
from datetime import datetime

def calc_business_seconds(start: pd.Timestamp, end: pd.Timestamp) -> int:
    # 计算两个时间之间扣除周末的总秒数
    if pd.isna(start) or pd.isna(end) or start >= end:
        return 0
    total_seconds = 0
    # 计算中间完整日期的有效时长
    full_days = pd.date_range(start=start.date() + pd.Timedelta(days=1), end=end.date() - pd.Timedelta(days=1))
    valid_full_days = full_days[full_days.weekday < 5]
    total_seconds += len(valid_full_days) * 86400
    # 计算起始日剩余时长
    if start.weekday() < 5:
        start_end_of_day = start.normalize() + pd.Timedelta(days=1)
        total_seconds += (start_end_of_day - start).total_seconds()
    # 计算结束日已过时长
    if end.weekday() < 5:
        end_start_of_day = end.normalize()
        total_seconds += (end - end_start_of_day).total_seconds()
    return int(total_seconds)

def strfdelta(total_seconds: int):
    hours = int(total_seconds // 3600)
    minutes = int((total_seconds % 3600) // 60)
    seconds = int(total_seconds % 60)
    return f"{hours:02}:{minutes:02}:{seconds:02}"

# 原有日期转换逻辑不变
df["Folder1"] = pd.to_datetime(df["Folder1"])
df["Folder2"] = pd.to_datetime(df["Folder2"])

bm1 = df["Folder1"].notna() & df["Folder2"].notna()
bm2 = df["Folder1"].notna() & df["Folder2"].isna()

# 修改Time1、Time2的计算逻辑
df.loc[bm1, "Time1"] = df.loc[bm1].apply(lambda row: strfdelta(calc_business_seconds(row["Folder1"], row["Folder2"])), axis=1)
df.loc[bm2, "Time2"] = df.loc[bm2].apply(lambda row: strfdelta(calc_business_seconds(row["Folder1"], datetime.now())), axis=1)

修改说明:

  • 新增calc_business_seconds函数,会自动过滤计算区间内的周六、周日,仅统计工作日的时长,你给出的示例中11月13、14日为周末会被自动扣除,计算得到的总秒数转成时长就是32小时,符合预期。
  • 调整了strfdelta的入参为直接接收总秒数,减少类型转换的冗余。
  • 时间差计算不再直接对两列做减法,而是通过行级别apply调用有效时长计算函数,再格式化输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:36:08