简体   繁体   中英

R - Convert Date Time as character into Seconds (numeric)

I am reading data time value from csv file stored as below

"2013-08-01 00:10:46"
"2013-08-01 00:10:51"
"2013-08-01 00:10:53"
"2013-08-01 00:11:04"
"2013-08-01 00:11:06"

While reading it is read as character and i want to convert it into seconds from 1970-01-01. I am able to achieve it using the below line of code but it takes ages to convert. Is there a better and faster way to achieve this

rstarttime  <- as.numeric(as.POSIXct(rdata$starttime,origin = "1970-01-01"))

You can use lubridate .

According to the following test, it can be around 12 times faster:

library(lubridate)
ttt <- c(
    "2013-08-01 00:10:46",
    "2013-08-01 00:10:51",
    "2013-08-01 00:10:53",
    "2013-08-01 00:11:04",
    "2013-08-01 00:11:06"
)

t <- Sys.time()
q <- as.numeric(as.POSIXct(rep(ttt,50000),origin = "1970-01-01"))
t1 <- Sys.time() - t

t <- Sys.time()
q <- time_length(interval(ymd("1970-01-01"), rep(ttt, 50000)), "second")
t2 <- Sys.time() - t

The values I obtained for t1 and t2 are 6 seconds and 0.5 seconds respectively. So lubridate performs around 12 times faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM