You need to enable JavaScript to run this app. Python导入的%H:%M:%S格式时间无法加减timedelta问题解决
优惠活动
大模型
产品
解决方案
定价
更多

Python导入的%H:%M:%S格式时间无法加减timedelta问题解决

Python时间运算报错修复方案

错误根因

你传入的close_time和open_time是符合%H:%M:%S格式的字符串类型,timedelta仅支持和datetime/time类型的对象执行算术运算,字符串和时间差类型不支持直接加减,因此触发报错。

修复步骤

  1. 先将传入的字符串格式时间通过datetime.strptime方法转换为datetime对象
  2. 对转换后的datetime对象执行timedelta加减运算
  3. 若后续业务需要字符串格式的结果,再通过strftime方法转换回%H:%M:%S格式即可

修复后代码

import datetime

def check_shuttertime(close_time, open_time, check_period):
    # 转换传入的字符串时间为datetime对象
    close_time_dt = datetime.datetime.strptime(close_time, "%H:%M:%S")
    open_time_dt = datetime.datetime.strptime(open_time, "%H:%M:%S")

    neg_adj_current_time = datetime.datetime.now() - datetime.timedelta(minutes=check_period+1)
    neg_adj_current_time = neg_adj_current_time.strftime("%H:%M:%S")
    pos_adj_current_time = datetime.datetime.now() + datetime.timedelta(minutes=check_period+1)
    pos_adj_current_time = pos_adj_current_time.strftime("%H:%M:%S")

    # 对datetime对象执行时间差运算
    close_time_adj = close_time_dt + datetime.timedelta(minutes=check_period+1)
    open_time_adj = open_time_dt - datetime.timedelta(minutes=check_period+1)

    # 可选:转换调整后的时间为字符串格式
    close_time_adj_str = close_time_adj.strftime("%H:%M:%S")
    open_time_adj_str = open_time_adj.strftime("%H:%M:%S")

    current_time = datetime.datetime.now().strftime("%H:%M:%S")
    # 后续业务逻辑自行补充

注意事项

  • 上述转换生成的datetime对象默认携带1900-01-01的日期信息,仅做当日内的时间运算不会影响结果
  • 如果业务逻辑需要处理跨天的时间计算,建议传入完整的年-月-日 时:分:秒格式的时间参数,避免日期截断导致的计算错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 18:36:03