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

如何将字符型HH:MM:SS格式时间转换为分钟并添加至数据集

将HH:MM:SS格式字符型变量转换为总分钟数并添加到数据集

下面提供两种实用方法,帮你快速完成需求:

方法1:优化你当前的拆分计算思路

你用separate拆分的思路完全可行,只需调整细节就能更高效完成,无需额外用cbind拼接数据集:

  • 加载tidyr和dplyr工具包
  • 拆分total_time_spend时,通过convert = TRUE参数直接将拆分出的小时、分钟、秒转为数值型
  • 计算总分钟数:小时×60 + 分钟 + 秒÷60(如果只需要整数分钟,可去掉秒的部分)
  • 可选:删除拆分产生的中间列

代码示例:

library(tidyr)
library(dplyr)

ride_history <- ride_history %>%
  separate(total_time_spend, into = c("hour", "minute_temp", "second"), sep = ":", convert = TRUE) %>%
  mutate(minute = hour * 60 + minute_temp + second / 60) %>%
  # 若不需要中间列,执行下面的删除操作
  select(-hour, -minute_temp, -second)

方法2:用lubridate包快速处理(更简洁)

lubridate是专门处理时间日期的工具包,能直接把HH:MM:SS格式的字符转成时间段,再快速计算总分钟数:

  • 加载lubridate和dplyr工具包
  • 用hms()函数将字符型时间转为小时-分钟-秒的时间段类型
  • 通过period_to_seconds()转成总秒数,再除以60得到总分钟数

代码示例:

library(lubridate)
library(dplyr)

ride_history <- ride_history %>%
  mutate(minute = period_to_seconds(hms(total_time_spend)) / 60)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:05:21