簡體   English   中英

在R中將difftime輸出為HH:MM:SS:mm

[英]Outputting difftime as HH:MM:SS:mm in R

我想標題說明了一切:我有一對用Sys.time()生成的POSIX時間對象,我希望以一致的方式顯示差異。 我希望時間范圍從毫秒到天不等,但是找不到找到以DD:HH:MM:SS:mm格式顯示difftime輸出的difftime

有什么簡潔的R方法可以做到這一點(理想情況下沒有包)?

帖子的主題和內容要求使用不同的格式,因此我們假設需要帖子正文中的那個,即DD:HH:MM:SS。

假設輸入x必須是秒的向量或difftime對象:

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM