3

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

Ixxie
  • 1,393
  • 1
  • 9
  • 17
  • 3
    If your purpose is to measure some piece of code, don't use `Sys.time(); expression2measure; Sys.time()` but `system.time(expression2measure)` – digEmAll Jul 11 '14 at 17:01

1 Answers1

9

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"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341