I have some timestamp
values such as "2018-06-09 23:59:59.946" and "2018-06-09 23:59:59.938" that are being recognized as a character string in R at the moment and I need them to be treated as a date or date-time object.
Below is the relevant code chunk:
# 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")
Below is the same code but with head(tradeOrders$timestamp)
& class(tradeOrders$timestamp)
between each step and the corresponding output so you can see what's going on.
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"
I have viewed a few other answers regarding working with R and timestamps that have nanosecond or millisecond precision, which assisted me in generating some of the code above. But now I'm having difficulty transforming the output into a date-time. I've looked into solutions involving library(nanotime)
as well as lubridate
but am stuck.
Can anyone assist me?
format
made them into text. The milliseconds are there in the originaltradeOrders$timestamp
, they just don't get printed by default.format
if you need to look at them temporarily, or you can set a global option for the session -options(digits.secs=3)
for example.