简体   繁体   中英

Outputting difftime as HH:MM:SS:mm in R

I guess the title says it all: I have a pair of POSIX time objects produced with Sys.time() and I want the difference displayed in a consistent manner. I expect times to vary from the order of magnitude of milliseconds to days, but cannot find a way to display the output of difftime in the format DD:HH:MM:SS:mm .

Any terse R methods to do this (ideally without packages)?

The subject and content of the post ask for different formats so we will assume that the one in the body of the post is desired, ie DD:HH:MM:SS .

Assuming the input, x , must be a vector of seconds or a difftime object:

Fmt <- function(x) UseMethod("Fmt")
Fmt.difftime <- function(x) {
     units(x) <- "secs"
     x <- unclass(x)
     NextMethod()
}
Fmt.default <- function(x) {
   y <- abs(x)
   sprintf("%s%02d:%02d:%02d:%02d", 
      ifelse(x < 0, "-", ""), # sign
      y %/% 86400,  # days
      y %% 86400 %/% 3600,  # hours 
      y %% 3600 %/% 60,  # minutes
      y %% 60 %/% 1) # seconds
}

# test
now <- Sys.time()
now100 <- now + 100

Fmt(now100 - now)
## [1] "00:00:01:40"

Fmt(now - now100)
## "-00:00:01:40"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM