format time span to show hours, minutes, seconds

format, r, time

Solution

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

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

Problem

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. 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" 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=':')) } ```

Original source