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

如何编写将时间标签反向转换为对应秒数的Python函数?

时间标签转总秒数函数实现

你可以直接使用以下代码完成反向转换,完全兼容你提供的秒转标签函数的输出格式:

def label_to_seconds_converter(time_label):
    # 匹配原函数0秒输出的特殊标签
    if time_label == "No info":
        return 0
    total = 0
    # 单位映射兼容单复数写法
    unit_second_value = {
        "hour": 3600,
        "hours": 3600,
        "minute": 60,
        "minutes": 60,
        "second": 1,
        "seconds": 1
    }
    # 拆分标签后按「数值+单位」成对遍历计算
    parts = time_label.split()
    for idx in range(0, len(parts), 2):
        num = int(parts[idx])
        unit = parts[idx+1].lower()
        total += num * unit_second_value[unit]
    return total

测试效果

# 你给出的预期用例
print(label_to_seconds_converter("5 Hours 54 Minutes 14 Seconds"))
# 输出:21254

# 其他边界场景验证
print(label_to_seconds_converter("1 Hour 0 Minutes 5 Seconds"))
# 输出:3605
print(label_to_seconds_converter("1 Minute 30 Seconds"))
# 输出:90
print(label_to_seconds_converter("No info"))
# 输出:0

内容的提问来源于stack exchange,提问作者Mehmet Güdük

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:15:03