Rahul Rahul - 3 months ago 21
R Question

How do I change the format of a char vector containing milliseconds to timeseries vector in R

I have a DF in R which has two character columns. The first column is a time series array and the second column contains continuous numbers. The time series field has time recorded in milliseconds. I am trying to convert this array to a date array. However whichever method I use to convert the same, I lose the milliseconds information.

Following is the dataframe:

time = c("08-08-2016 09:16:33.430","08-08-2016 09:16:37.930")
values <- c(45,21)
my_data <- data.frame(time,values)

I would like to preserve the millisecond information. However, as I convert the time char array using following method, I lose the milliseconds (O/P time array= 2016-08-08 09:16:33,08-08-2016 09:16:37) .

my_data$time=strptime(my_data$time,format="%m-%d-%Y %H:%M:%S.%OS")

I also tried using as.POSIXct, as.Date functions but could not resolve. Can someone please help?


You have a standard-enough format so that anytime can parse this automagically with additional input from you:

R> timevec <- c("08-08-2016 09:16:33.430","08-08-2016 09:16:37.930")
R> anytime(timevec)
[1] "2016-08-08 09:16:33.43 CDT" "2016-08-08 09:16:37.93 CDT"

I tend to have options(digits.secs=6) set by default which is why the display also shows the fractional seconds.