guyabel
guyabel

Reputation: 8366

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.

Upvotes: 3

Views: 8556

Answers (2)

Jay Bee
Jay Bee

Reputation: 572

Another possible approach.

We divide our milliseconds values by 1000 (to make them seconds).

Then plug that into the seconds_to_period() function from the lubridate package to turn them into times.

And then use the hms function from the hms package to put them into a HH:MM:SS format.

library(dplyr)
library(lubridate)
library(hms)

x <- c(119254, 246973, 267492)

y <- seconds_to_period(round(x / 1000))

z <- hms::hms(y)

For output:

00:01:59
00:04:07
00:04:27

Note that with this approach it has rounded 246973 milliseconds (or 4 minutes and 6.973 seconds) to 4 minutes and 7 seconds.

It is a bit clunky but works for my non-coder brain. With thanks to SamR at: How do I convert milliseconds to minutes and seconds?

Upvotes: 0

IRTFM
IRTFM

Reputation: 263301

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"

Upvotes: 8

Related Questions