How to format fractional seconds in POSIXct in r

亡梦爱人 提交于 2020-02-24 11:30:07

问题


I have read other questions regarding this topic but they do not seem to work on my dataset:

              Timestamp Bid.price Ask.price Bid.volume Ask.volume
 20070313 07:01:04:762  11.14122  11.14478   4.539397   1.891416
 20070313 07:01:07:608  11.13930  11.14670   1.277812   3.066750
 20070313 07:01:08:701  11.14095  11.14505   0.050396   0.050396
 20070313 07:01:11:275  11.14098  11.14502   0.226505   0.543613
 20070313 07:01:13:884  11.13930  11.14670   0.322856   0.774855
 20070313 07:01:16:588  11.13930  11.14670   0.405654   0.973569

I have tried:

as.POSIXct(fx[,1], format="%y%m%d %H:%M:%S:%OS3")
as.POSIXct(paste(fx[,1]), format="%y%m%d %H:%M:%S:%OS3")
as.POSIXct(paste(fx[,1]), format="%y%m%d %H:%M:%S")

but all I get are NAs ...

How do I work around this?

Here is the dataset:

fx <- structure(list(Timestamp = c("20070313 07:01:04:762", "20070313 07:01:07:608", 
"20070313 07:01:08:701", "20070313 07:01:11:275", "20070313 07:01:13:884", 
"20070313 07:01:16:588"), Bid.price = c(11.14122, 11.1393, 11.14095, 
11.14098, 11.1393, 11.1393), Ask.price = c(11.14478, 11.1467, 
11.14505, 11.14502, 11.1467, 11.1467), Bid.volume = c(4.5393967628479, 
1.27781200408936, 0.0503959991037846, 0.226504996418953, 0.3228560090065, 
0.405654013156891), Ask.volume = c(1.89141595363617, 3.06675004959106, 
0.0503959991037846, 0.543613016605377, 0.774855017662048, 0.973568975925446
)), .Names = c("Timestamp", "Bid.price", "Ask.price", "Bid.volume", 
"Ask.volume"), row.names = c(NA, 6L), class = "data.frame")

回答1:


Because Timestamp has a : between whole seconds and fractional seconds, and there isn't a time parsing string ("conversion specification", e.g. %Y) for fractions of seconds without the whole, you need to change the last : to a . so you can parse it with %OS. sub can take care of it, looking for

  • a colon :
  • followed by 3 digits \\d{3}, captured (...)
  • followed by the end of the line $,

and replacing it with

  • a period .
  • followed by the captured group.

Further, if you want to see the fractional seconds that it's parsing, you'll need to set the digits.secs option:

options(digits.secs = 3)
strptime(sub(':(\\d{3})$', '.\\1', fx$Timestamp), '%Y%m%d %H:%M:%OS')
# [1] "2007-03-13 07:01:04.762 EDT" "2007-03-13 07:01:07.608 EDT" "2007-03-13 07:01:08.700 EDT"
# [4] "2007-03-13 07:01:11.275 EDT" "2007-03-13 07:01:13.884 EDT" "2007-03-13 07:01:16.588 EDT"

Note that strptime inserts the local timezone (EDT for me at the moment), but you can set that to whatever you like (or whatever it should be for your data) with its tz argument.



来源:https://stackoverflow.com/questions/36124889/how-to-format-fractional-seconds-in-posixct-in-r

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