Search code examples
r

convert milliseconds to time in R


I have a set of times in milliseconds that I want to convert to mm:ss (to compare with a similar set). For example I have

 x<-c(119254, 246973, 267492)

I can work out the minutes by the arithmetic

 > x/1000/60
 [1] 1.987567 4.116217 4.458200

Not sure how to get to %M:%S format, or if there is a proper way to take the milliseconds and convert without the arithmetic.


Solution

  • Just add the seconds to a DateTime object and format.POSIXct will take care of the calculations for display. You do not need to divide by 60 since POSIXct times are in seconds:

    > as.POSIXct(Sys.Date())+x/1000
    #[1] "2013-03-07 16:01:59 PST" "2013-03-07 16:04:06 PST" "2013-03-07 16:04:27 PST"
    
    > format( as.POSIXct(Sys.Date())+x/1000, "%M:%S")
    #[1] "01:59" "04:06" "04:27"