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

如何在R语言中将H/M/S格式的时长字符串转换为秒数

解决方案

方法1:基础R实现(无需安装额外包)

通过正则匹配分别提取小时、分钟、秒对应的数值,无对应单位时默认补0,再按换算规则求和:

playtimes <- c("1H18M20S", "1H27M5S", "18M27S", "56M38S", "21S")

# 提取各单位数值
hours <- ifelse(grepl("H", playtimes), as.numeric(sub("^(\\d+)H.*", "\\1", playtimes)), 0)
minutes <- ifelse(grepl("M", playtimes), as.numeric(sub(".*?(\\d+)M.*", "\\1", playtimes)), 0)
seconds <- ifelse(grepl("S", playtimes), as.numeric(sub(".*?(\\d+)S$", "\\1", playtimes)), 0)

# 计算总秒数
playtimeInSeconds <- hours * 3600 + minutes * 60 + seconds

运行后得到的playtimeInSeconds结果和你给出的示例完全一致。

方法2:lubridate包简化实现(推荐)

借助时间处理专用包的内置解析能力,一行代码即可完成转换:

# 未安装包先执行 install.packages("lubridate")
library(lubridate)

playtimeInSeconds <- as.numeric(duration(playtimes))

lubridate的duration函数原生支持H/M/S格式的时长解析,转换为数值类型后默认单位就是秒。


原代码的问题在于没有适配带H单位的场景,遇到包含H的字符串时,提取分钟的逻辑会把H及之前的内容也保留下来,导致数值转换出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:27:04