使用空格和毫秒将列转换为日期格式

时间:2014-06-25 03:30:01

标签: r quantmod strptime posixlt

我一直试图解决这个问题几天,似乎在R中进行简单的日期列转换时遇到了困难。

我需要格式化日期和时间才能使用to.period命令。我想格式化mydata $ Time列,并将整个系列转换为4hr OHLC吧。

以下是代码输入;

> mydata = read.csv("AUDJPY.csv")
> colnames(mydata) <- c("Pair","Time","Bid","Ask")
> head(mydata)
     Pair                  Time    Bid    Ask
1 AUD/JPY 20140501 00:00:00.301 94.874 94.893
2 AUD/JPY 20140501 00:00:00.312 94.876 94.895
3 AUD/JPY 20140501 00:00:00.316 94.876 94.882
4 AUD/JPY 20140501 00:00:00.317 94.877 94.884
5 AUD/JPY 20140501 00:00:00.403 94.877 94.885
6 AUD/JPY 20140501 00:00:00.420 94.877 94.887
> mydata$Time <- strptime(as.character(mydata$Time),"%Y%m%d_%H:%M:%S.%f")
> head(mydata)
     Pair Time    Bid    Ask
1 AUD/JPY <NA> 94.874 94.893
2 AUD/JPY <NA> 94.876 94.895
3 AUD/JPY <NA> 94.876 94.882
4 AUD/JPY <NA> 94.877 94.884
5 AUD/JPY <NA> 94.877 94.885
6 AUD/JPY <NA> 94.877 94.887
> class(mydata$Time)
[1] "POSIXlt" "POSIXt" 
> 

请帮忙!

1 个答案:

答案 0 :(得分:4)

对于带小数的秒,您希望使用“%OS”而不是“%S”。后者忽略了价值。如果您的格式有空格,您可以在格式字符串中包含空格。

观察

x<-c("20140501 00:00:00.301","20140501 00:00:00.420")

a<-strptime(x,"%Y%m%d %H:%M:%OS");
a
# [1] "2014-05-01 00:00:00 EDT" "2014-05-01 00:00:00 EDT"
a$sec
# [1] 0.301 0.420

当您显示日期类的值时,默认情况下R不显示小数默认值,您可以看到它们存储在对象本身中。