将字符串转换为日期时间

时间:2017-03-24 19:50:36

标签: r datetime posixct strptime

我正在尝试将数据集加载到r中,并将列的类型更改为datetime。

对于不同的案例,

strptimeas.POSIXctas.Date应该有效;

这是我的代码:

a <- structure(list(DATE = c("01/01/2011 12:00:00", "01/02/2011 12:00:00", 
   "01/03/2011 12:00:00", "01/04/2011 12:00:00", "01/05/2011 12:00:00", 
   "01/06/2011 12:00:00"), VAL = c(65.34447917, 65.23983333, 65.03183333, 
   64.89107292, 64.83333333, 64.848625), id = c("VT1-1", "VT1-1", "VT1-1", 
   "VT1-1", "VT1-1", "VT1-1")), .Names = c("DATE", "VAL", "id"), row.names = c(NA, -6L), 
   class = c("tbl_df", "tbl", "data.frame"))

b1 <- as.POSIXct(a$DATE, format = "%m/%d/%y %H:%M:%S")
b2 <- strptime(a$DATE,"%m/%d/%Y %H:%M/%S")

但他们只是返回NA。这很可能是一个错字;但是在处理不同的日期时间格式时如何避免这种情况呢?

1 个答案:

答案 0 :(得分:1)

R> library(anytime)
R> anytime(a$DATE)
[1] "2011-01-01 12:00:00 CST" "2011-01-02 12:00:00 CST" "2011-01-03 12:00:00 CST"
[4] "2011-01-04 12:00:00 CST" "2011-01-05 12:00:00 CST" "2011-01-06 12:00:00 CST"
R> 

随时打开软件包是为了简化这一过程 - 您不需要提供可能出错的格式,它只是尝试了许多合理的格式。对于“合理”的输入,它只是起作用