Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format time span to show hours, minutes, seconds

Tags:

time

format

r

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=':'))
}
like image 873
getting-there Avatar asked Jun 13 '12 15:06

getting-there


People also ask

How do you convert TimeSpan to hours?

A TimeSpan value can be represented as [-]d. hh:mm:ss. ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. The value of the Hours property is the hours component, hh.

What is TimeSpan format?

A TimeSpan format string defines the string representation of a TimeSpan value that results from a formatting operation. A custom format string consists of one or more custom TimeSpan format specifiers along with any number of literal characters.

What is time span in C#?

C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.


1 Answers

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())
like image 134
Joshua Ulrich Avatar answered Oct 17 '22 07:10

Joshua Ulrich