Search code examples
rtimedata-scienceiso8601

Convert proprietary time duration format to milliseconds


Here is an example of the time duration format:

16984  = 16 second 984 milliseconds
214032 = 2 minutes 14 seconds, 032 milliseconds
1649871 = 16 minutes 49 seconds and 871 milliseconds

So it looks like the time duration format in human readable format is minutes:seconds:milliseconds

I wrote a function to convert it but I know its not foolproof. I know that the length of the string will be up to 2

convert.to.ms <- function(str) {

  str <- as.numeric(str)

  ms <- c()
  ss <- c()
  min <- c()
  nchar(str)
  total.ms <-c()

  if(nchar(str) == 6) {

    ms  <- as.numeric(substr(str, nchar(str)-2, nchar(str)))

    ss  <- as.numeric(substr(str, nchar(str)-4, nchar(str)-3))

    min <- as.numeric(substr(str, 0, 1))
    total.ms <- (sum (ms + ss*1000 + min*60000))


  } else if(nchar(str) == 5) {

    ms  <- as.numeric(substr(str, nchar(str)-2, nchar(str)))

    ss  <- as.numeric(substr(str, nchar(str)-4, nchar(str)-3))
    total.ms <- (sum (ms + ss*1000))
  }
  total.ms
}

I've tried using lubridate to no avail


Solution

  • Embrace the numericity of your input

    prop.time.format.to.milliseconds <- function(ptf) {
        ms <- as.numeric(ptf) %% 1000
        ss <- floor(as.numeric(ptf)/1000) %% 100
        mm <- floor(as.numeric(ptf)/100000)
        mm*60000 + ss*1000 + ms
    }