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

r

Solution

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, i.e. 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"

Problem

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)?

Original source