简体   繁体   中英

Convert character date and time with milliseconds to numeric in R

I have the following Timestamp vector:

Timestamp <- c("30-09-2016 11:45:00.000", "01-10-2016 06:19:57.860", "01-10-2016 06:20:46.393")

Timestamp is part of a table (unfortunately it doesn't seem to be a data.frame...) that contains other columns of degrees and weight:

  Timestamp Weight Degrees
1 30-09-2016 11:45:00.000 38.19 40.00 
2 01-10-2016 06:19:57.860 39.12 40.00 
3 01-10-2016 06:20:46.393 42.11 41.00

I would like to plot Weight against Timestamp, but the mode of Timestamp is "character", which means that the x-axis is not read properly. Would you have any suggestion to convert this to numeric?

I have tried as.Date(Timestamp,format='%d-%m-%Y %H:%M:%OS3') but it does not seem to work.

As Erdem said, with as.POSIXct with %OS for seconds

t1 <- c("30-09-2016 11:45:00.000", "01-10-2016 06:19:57.860", "01-10-2016 06:20:46.393")     
t2 <- as.POSIXct(t1,format = "%d-%m-%Y  %H:%M:%OS")

note that timestamps are displayed/printed in whole seconds by default; see digits.secs in ?options

t2
 [1] "2016-09-30 11:45:00 EDT" "2016-10-01 06:19:57 EDT" "2016-10-01 06:20:46 EDT"

but millisecond resolution is maintained internally

diff(t2)
 Time differences in secs
 [1] 66897.860    48.533

if you want to display/print millisecond resolution set by using

options(digits.secs=3)
t2
 [1] "2016-09-30 11:45:00.000 EDT" "2016-10-01 06:19:57.859 EDT" "2016-10-01 06:20:46.392 EDT"

使用as.POSIXct

as.POSIXct(Timestamp,format = "%d-%m-%Y  %H:%M:%S.%OS")

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