强制将毫秒精度的时间戳转换为R中可识别的日期时间对象中的字符

时间:2019-03-13 22:10:01

标签: r date datetime timestamp milliseconds

我有一些timestamp值,例如“ 2018-06-09 23:59:59.946”和“ 2018-06-09 23:59:59.938”被识别为R中的字符串此刻,我需要将它们视为日期或日期时间对象。

下面是相关的代码块:

# Convert the timestamp from nanoseconds to millisecond precision
tradeOrders$timestamp = 
  as.POSIXct(gsub("D", " ", tradeOrders$timestamp))

tradeOrders$timestamp = 
  as.POSIXct(tradeOrders$timestamp, "%Y-%m-%d %H:%M:%OS3")

tradeOrders$timestamp = 
  format(tradeOrders$timestamp, "%Y-%m-%d %H:%M:%OS3")

下面是相同的代码,但是在每个步骤和相应的输出之间使用head(tradeOrders$timestamp)class(tradeOrders$timestamp),因此您可以查看正在发生的情况。

R> tradeOrders =
+   tradeOrders[order(tradeOrders$timestamp, decreasing = TRUE), ]
R> # Convert the timestamp from nanoseconds to millisecond precision
R> tradeOrders$timestamp = 
+   as.POSIXct(gsub("D", " ", tradeOrders$timestamp))
R> head(tradeOrders$timestamp)
[1] "2018-06-09 23:59:59 CDT" "2018-06-09 23:59:59 CDT"
[3] "2018-06-09 23:59:59 CDT" "2018-06-09 23:59:59 CDT"
[5] "2018-06-09 23:59:59 CDT" "2018-06-09 23:59:59 CDT"
R> class(tradeOrders$timestamp)
[1] "POSIXct" "POSIXt" 
R> tradeOrders$timestamp = 
+   as.POSIXct(tradeOrders$timestamp, "%Y-%m-%d %H:%M:%OS3")
R> head(tradeOrders$timestamp)
[1] "2018-06-09 23:59:59 CDT" "2018-06-09 23:59:59 CDT"
[3] "2018-06-09 23:59:59 CDT" "2018-06-09 23:59:59 CDT"
[5] "2018-06-09 23:59:59 CDT" "2018-06-09 23:59:59 CDT"
R> class(tradeOrders$timestamp)
[1] "POSIXct" "POSIXt" 
R> class(tradeOrders$timestamp)
[1] "POSIXct" "POSIXt" 
R> tradeOrders$timestamp = 
+   format(tradeOrders$timestamp, "%Y-%m-%d %H:%M:%OS3")
R> head(tradeOrders$timestamp)
[1] "2018-06-09 23:59:59.946" "2018-06-09 23:59:59.938"
[3] "2018-06-09 23:59:59.583" "2018-06-09 23:59:59.374"
[5] "2018-06-09 23:59:59.257" "2018-06-09 23:59:59.225"
R> class(tradeOrders$timestamp)
[1] "character"

关于R和具有纳秒或毫秒精度的时间戳,我已经查看了其他一些答案,这有助于我生成上面的一些代码。但是现在我很难将输出转换为日期时间。我已经研究了涉及library(nanotime)lubridate的解决方案,但遇到了麻烦。

有人可以帮助我吗?

0 个答案:

没有答案