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

如何在R中将毫秒转换为MM:SS格式的分秒?

如何在R中将毫秒值转换为MM:SS格式的分秒?

要实现毫秒到MM:SS分秒格式的转换,核心是先将毫秒转为四舍五入后的总秒数,再拆分分钟和秒并格式化为两位数的分秒结构。以下是几种可行的实现方式:

测试数据

首先明确测试数据集:

df <- data.frame(
  ID = c("ID1", "ID2", "ID3"),
  duration = c(1723456, 1834537, 1945678)
)

方法1:基础R原生实现

无需额外包,手动计算并格式化:

# 转换毫秒为秒并四舍五入
total_seconds <- round(df$duration / 1000)
# 拆分分钟和秒
minutes <- total_seconds %/% 60
seconds <- total_seconds %% 60
# 格式化为MM:SS(确保两位数)
df$duration <- sprintf("%02d:%02d", minutes, seconds)

方法2:dplyr + lubridate 实现

借助tidyverse工具链,更贴合数据处理流程:

library(dplyr)
library(lubridate)

df <- df %>%
  mutate(
    # 转成四舍五入后的秒数,再转为周期对象
    duration_period = seconds_to_period(round(duration / 1000)),
    # 提取分钟和秒并格式化
    duration = sprintf("%02d:%02d", minute(duration_period), second(duration_period))
  ) %>%
  select(-duration_period) # 移除中间计算列

方法3:hms包实现

如果习惯用hms处理时间格式,可先处理四舍五入再指定格式化规则:

library(dplyr)
library(hms)

df <- df %>%
  mutate(
    # 生成hms对象(基于四舍五入后的秒数)
    duration_hms = hms(seconds = round(duration / 1000)),
    # 只保留分秒部分
    duration = format(duration_hms, "%M:%S")
  ) %>%
  select(-duration_hms)

原代码问题说明

你之前的代码未达到预期的原因有两点:

  1. 没有对转换后的秒数进行四舍五入,导致保留了小数秒;
  2. hms::hms()默认输出HH:MM:SS格式,会显示多余的小时位(00:xx:xx)。

最终输出结果

处理后的数据集如下:

IDduration
ID128:43
ID230:35
ID332:26

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 14:12:43