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

如何修复秒转dd:hh:mm:ss函数输入None时divmod报TypeError的问题

报错根因

该错误是因为输入参数s为None(即你提到的null值)时,divmod函数不支持对None类型和整数做运算导致的。

修复方案

在函数入口处增加None值判断,根据你的业务需求返回对应默认值即可,以下是两种常用实现:

  • 输入为None时返回空字符串,适合需要过滤空值的场景
def to_hms(s):
    if s is None:
        return ''
    m, s = divmod(s, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    return '{}:{:0>2}:{:0>2}:{:0>2}'.format(d, h, m, s)
  • 输入为None时返回全0格式,适合需要统一输出格式的场景
def to_hms(s):
    if s is None:
        return '0:00:00:00'
    m, s = divmod(s, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    return '{}:{:0>2}:{:0>2}:{:0>2}'.format(d, h, m, s)

如果需要兼容更多异常输入(比如负数、非数值类型),可以进一步扩展判断逻辑:

def to_hms(s):
    # 过滤非数值、负数输入
    if not isinstance(s, (int, float)) or s < 0:
        return ''
    m, s = divmod(s, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    return '{}:{:0>2}:{:0>2}:{:0>2}'.format(d, h, m, s)

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

相关产品推荐
方舟 Agent Plan

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

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