格式化时间跨度以显示小时,分钟,秒

时间:2021-05-07 21:31:50

I've been trying to find a simple way of formatting the output from difftime into HH:MM:SS.ms. So far I haven't come across anything which I was surprised by.

我一直试图找到一种简单的方法,将difftime的输出格式化为HH:MM:SS.ms。到目前为止,我还没有遇到任何我感到惊讶的事情。

I did write the function below which almost does it. The limitation is the presentation of the numbers as significant single digits. eg 2hr, 3mins, 4.5secs becomes "2:3:4.5" instead of "02:03:04.5"

我确实编写了下面几乎完成的功能。限制是将数字表示为重要的单个数字。例如2小时,3分钟,4.5秒变为“2:3:4.5”而不是“02:03:04.5”

Does anyone have a better suggestion?

有没有人有更好的建议?

format.timediff <- function(start_time) {
    diff = as.numeric(difftime(Sys.time(), start_time, units="mins"))
    hr <- diff%/%60
    min <- floor(diff - hr * 60)
    sec <- round(diff%%1 * 60,digits=2)

    return(paste(hr,min,sec,sep=':'))
}

2 个解决方案

#1


11  

In addition to @GSee's comment, you could use a function like this:

除了@ GSee的评论,你可以使用这样的函数:

f <- function(start_time) {
  start_time <- as.POSIXct(start_time)
  dt <- difftime(Sys.time(), start_time, units="secs")
  # Since you only want the H:M:S, we can ignore the date...
  # but you have to be careful about time-zone issues
  format(.POSIXct(dt,tz="GMT"), "%H:%M:%S")
}
f(Sys.Date())

#2


0  

Merge_Charge_Point$Duration<- difftime(Merge_Charge_Point$EndConnectionDateTime, Merge_Charge_Point$StartConnectionDateTime, units="secs")

This is the code. But this code transforms the data in to seconds but the outcome should be a time string.

这是代码。但是这段代码将数据转换为秒,但结果应该是时间字符串。

#1


11  

In addition to @GSee's comment, you could use a function like this:

除了@ GSee的评论,你可以使用这样的函数:

f <- function(start_time) {
  start_time <- as.POSIXct(start_time)
  dt <- difftime(Sys.time(), start_time, units="secs")
  # Since you only want the H:M:S, we can ignore the date...
  # but you have to be careful about time-zone issues
  format(.POSIXct(dt,tz="GMT"), "%H:%M:%S")
}
f(Sys.Date())

#2


0  

Merge_Charge_Point$Duration<- difftime(Merge_Charge_Point$EndConnectionDateTime, Merge_Charge_Point$StartConnectionDateTime, units="secs")

This is the code. But this code transforms the data in to seconds but the outcome should be a time string.

这是代码。但是这段代码将数据转换为秒,但结果应该是时间字符串。