Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fast conversion from string time to milliseconds

Tags:

string

r

For a vector or list of times, I'd like to go from a string time, e.g. 12:34:56.789 to milliseconds from midnight, which would be equal to 45296789.

This is what I do now:

toms = function(time) {
  sapply(strsplit(time, ':', fixed = T),
         function(x) sum(as.numeric(x)*c(3600000,60000,1000)))
}

and would like to do it faster.

Here's an example data set for benchmarking:

times = rep('12:34:56.789', 1e6)

system.time(toms(times))
#   user  system elapsed 
#   9.00    0.04    9.05
like image 650
eddi Avatar asked Aug 21 '13 20:08

eddi


People also ask

How do you convert string to milliseconds?

Using SimpleDateFormat With SimpleDateFormat , we can simply pass our date format into the constructor and parse dateStr to get a Date object. Calling getTime() will return the milliseconds. SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = sdf.

How do you convert milliseconds to strings in Java?

toMinutes(millis) - (hours * 60); long seconds = TimeUnit. MILLISECONDS. toSeconds(millis) - ((hours * 60 * 60) + (minutes * 60)); Use String.

How do you calculate time in milliseconds?

The time in milliseconds is equal to the seconds multiplied by 1,000.


1 Answers

You could use the fasttime package, which seems to be about an order of magnitude faster.

library(fasttime)
fasttoms <- function(time) {
  1000*unclass(fastPOSIXct(paste("1970-01-01",time)))
}
times <- rep('12:34:56.789', 1e6)
system.time(toms(times))
#   user  system elapsed 
#   6.61    0.03    6.68 
system.time(fasttoms(times))
#   user  system elapsed 
#   0.53    0.00    0.53
identical(fasttoms(times),toms(times))
# [1] TRUE
like image 61
Joshua Ulrich Avatar answered Sep 28 '22 02:09

Joshua Ulrich