Convert seconds to days: hours:minutes:seconds
You may try
library(lubridate)seconds_to_period(86400)#[1] "1d 0H 0M 0S"seconds_to_period(48000)#[1] "13H 20M 0S"
If you need to format
td <- seconds_to_period(86400)sprintf('%02d %02d:%02d:%02d', day(td), td@hour, minute(td), second(td))#[1] "01 00:00:00"
If it spans for >99
days,
td <- seconds_to_period(1e7)sprintf('%03d %02d:%02d:%02d', day(td), td@hour, minute(td), second(td))#[1] "115 17:46:40"
Using base R, the following should work:
dhms <- 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"
This also works using seconds.to.hms
from kimisc
, though not as elegant as @akrun's answer:
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+", .)
Result:
[1] "1 0:00:00"[1] "0 13:20:00"[1] "115 17:46:40"