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
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.
toMinutes(millis) - (hours * 60); long seconds = TimeUnit. MILLISECONDS. toSeconds(millis) - ((hours * 60 * 60) + (minutes * 60)); Use String.
The time in milliseconds is equal to the seconds multiplied by 1,000.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With