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

如何在Python3中将时/分/秒格式字符串转换为整数秒数

问题描述

假设有以下字符串类型的值:

str_one = '03H 49m 06s'
str_two = '18m 23s'
str_three = '56s'

如何将这些字符串转换为整数类型,得到如下对应输出?

13746 
1103
56
解决方案

经过梳理,我写了一个名为from_str_to_seconds的自定义函数,它支持接收以下三种格式的字符串作为输入:

  • 00H 00m 00s
  • 00m 00s
  • 00s

函数逻辑是提取字符串中的数字部分,转换为整数后乘以对应的时间换算系数,最后求和得到总秒数:

def from_str_to_seconds(string: str):
    if 'H' not in string:
        if 'm' not in string:
            seconds = int(string[:-1])
            return seconds
        else:
            seconds = (int(string[:2])*60)+int(string[-3:-1])
            return seconds
    else:
        seconds = (int(string[:2])*3600)+(int(string[-7:-5])*60)+int(string[-3:-1])
        return seconds
测试结果
from_str_to_seconds('03H 49m 06s')
Out[2]: 13746

from_str_to_seconds('18m 23s')
Out[3]: 1103

from_str_to_seconds('56s')
Out[4]: 56

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:16:10