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

将含hours、minutes、seconds的字符串转换为HH:MM:SS格式

如何将时长描述字符串转换为HH:MM:SS格式?

核心思路

这类字符串的特点是包含「小时(hour)、分钟(minute)、秒(second)」的任意组合,部分单位可能缺失。我们可以通过正则表达式提取各单位的数值,补全缺失单位为0,再格式化为两位数字的HH:MM:SS格式。

具体实现(Python示例)

import re

def convert_duration_to_hhmmss(duration_str):
    # 初始化各时间单位为0
    hours = 0
    minutes = 0
    seconds = 0
    
    # 匹配数字+时间单位的正则,兼容单复数(hour/hours、minute/minutes等)
    pattern = r'(\d+)\s*(hour|minute|second)s?'
    matches = re.findall(pattern, duration_str, re.IGNORECASE)
    
    # 遍历匹配结果,赋值对应单位
    for value, unit in matches:
        num = int(value)
        if unit.lower() == 'hour':
            hours = num
        elif unit.lower() == 'minute':
            minutes = num
        elif unit.lower() == 'second':
            seconds = num
    
    # 格式化为HH:MM:SS,不足两位补0
    return f"{hours:02d}:{minutes:02d}:{seconds:02d}"

# 测试示例输入
test_cases = [
    "1 hour, 27 minutes",
    "45 minutes,16 seconds",
    "31 seconds"
]

for case in test_cases:
    print(convert_duration_to_hhmmss(case))

输出结果

01:27:00
00:45:16
00:00:31

说明

  • 正则表达式r'(\d+)\s*(hour|minute|second)s?'可以匹配带/不带空格的数值+单位组合(比如45 minutes或16 seconds,甚至1hour这种无空格的情况),同时兼容单复数(hour和hours都能匹配)。
  • 用re.IGNORECASE忽略大小写,所以输入中的Hour/MINUTE等大小写变体也能正常处理。
  • 最后通过f"{x:02d}"将每个单位格式化为两位数字,不足时自动补0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:25:04