将带有毫秒的字符日期和时间转换为 R 中的数字 [英] Convert character date and time with milliseconds to numeric in R

查看:72
本文介绍了将带有毫秒的字符日期和时间转换为 R 中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下时间戳向量:

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

时间戳是包含其他度数和权重列的表的一部分(不幸的是它似乎不是 data.frame...):

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

我想根据时间戳绘制权重,但是时间戳的模式是字符",这意味着无法正确读取 x 轴.您有什么建议可以将其转换为数字吗?

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?

我已经尝试过 as.Date(Timestamp,format='%d-%m-%Y %H:%M:%OS3') 但它似乎不起作用.>

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

推荐答案

正如 Erdem 所说,用 as.POSIXct%OS

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")

请注意,时间戳默认以整秒显示/打印;参见 ?options

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"

这篇关于将带有毫秒的字符日期和时间转换为 R 中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆