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

前端 未结 1 983
借酒劲吻你
借酒劲吻你 2020-12-07 05:15

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

相关标签:
1条回答
  • 2020-12-07 06:13

    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"
    
    0 讨论(0)
提交回复
热议问题