我想在R中将秒转换为小时、分钟和秒。
示例
86400seconds-1day
gmdate("d H:i:s",86400)
这是我尝试的方式。
library(lubridate)
seconds_to_period(86400)
#[1] "1d 0H 0M 0S"
seconds_to_period(48000)
#[1] "13H 20M 0S"
如果您需要格式化
td <- seconds_to_period(86400)
sprintf('%02d %02d:%02d:%02d', day(td), td@hour, minute(td), second(td))
#[1] "01 00:00:00"
如果持续时间超过>99
天,
td <- seconds_to_period(1e7)
sprintf('%03d %02d:%02d:%02d', day(td), td@hour, minute(td), second(td))
#[1] "115 17:46:40"
%03d %02d:%02d:%02g
来打印出秒数的小数值。或者,您需要将其四舍五入以避免sprintf
的错误,因为%d
仅适用于整数。例如,请参见:https://dev59.com/114d5IYBdhLWcg3wJvwp - iradhms <- function(t){
paste(t %/% (60*60*24)
,paste(formatC(t %/% (60*60) %% 24, width = 2, format = "d", flag = "0")
,formatC(t %/% 60 %% 60, width = 2, format = "d", flag = "0")
,formatC(t %% 60, width = 2, format = "d", flag = "0")
,sep = ":"
)
)
}
> dhms(86400)
[1] "1 00:00:00"
> dhms(48000)
[1] "0 13:20:00"
> dhms(1e7)
[1] "115 17:46:40"
> dhms(c(86400, 48000, 1e7))
[1] "1 00:00:00" "0 13:20:00" "115 17:46:40"
使用kimisc
中的seconds.to.hms
也可以实现这一功能,但不如@akrun的回答优雅:
library(kimisc)
library(dplyr)
library(stringr)
HMS = seconds.to.hms(86400)
HMS = seconds.to.hms(48000)
HMS = seconds.to.hms(1e7)
HMS %>%
str_extract("^\\d+") %>%
as.numeric() %>%
{paste(.%/%24, .%%24)} %>%
str_replace(HMS, "^\\d+", .)
结果:
[1] "1 0:00:00"
[1] "0 13:20:00"
[1] "115 17:46:40"
my_seconds_to_period = function(x) {
days = round(x %/% (60 * 60 * 24))
hours = round((x - days*60*60*24) %/% (60 * 60))
minutes = round((x - days*60*60*24 - hours*60*60) %/% 60)
seconds = round(x - days*60*60*24 - hours*60*60 - minutes*60)
days_str = ifelse(days == 0, "", paste0(days, "d "))
hours_str = ifelse((hours == 0 & days == 0), "", paste0(hours, "H "))
minutes_str = ifelse((minutes == 0 & days == 0 & hours == 0), "", paste0(minutes, "M "))
seconds_str = paste0(seconds, "S")
final_str = paste0(days_str, hours_str, minutes_str, seconds_str)
return(final_str)
}
my_seconds_to_period(100000)
[1] "1d 3H 46M 40S"
随意使用或调整。