Convert character date and time with milliseconds to numeric in R

↘锁芯ラ 提交于 2020-01-04 05:48:05

问题


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.


回答1:


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"



回答2:


With as.POSIXct

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


来源:https://stackoverflow.com/questions/43471386/convert-character-date-and-time-with-milliseconds-to-numeric-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!