2017-01-06 82 views
2

我的data.table有一个“模糊”日期时间格式的列:“12/1/2016 15:30”。如何将此日期时间转换为R可在data.table中识别的格式,而不使用strptime()并获取最初转换为POSIXlt的警告消息。这个过程很有效,但警告让我觉得还有另一种方式。如何在不使用strptime的情况下转换data.table中的模糊日期时间列?

我的数据表:

my_dates <- c("12/1/2016 15:30", "12/1/2016 15:31", "12/1/2016 15:32") 
this <- c("a", "b", "c") 
that <- c(1, 2, 3) 

my_table <- data.table(my_dates, this, that) 

my_table 
    my_dates   this that 
1: 12/1/2016 15:30 1 a 
2: 12/1/2016 15:31 2 b 
3: 12/1/2016 15:32 3 c 

my_table[, my_dates := as.POSIXct(strptime(my_dates, "%m/%d/%Y %H:%M"))] 

Warning message: 
In strptime(my_dates, "%m/%d/%Y %H:%M") : 
POSIXlt column type detected and converted to POSIXct. We do not 
recommend use of POSIXlt at all because it uses 40 bytes to store one date. 

所以,它的工作原理,但我敢打赌,有,我只是忽略了,以避免该警告的技术。我使用了my_table[, dates:= as.POSIXct(dates)],但这会减少日期时间的一部分。我也尝试过my_table[, dates:= as.POSIXct(dates, "%m/%d/%Y %H:%M")],并且时间也会减少,并重新发出警告。

谢谢你的建议。

回答

2

我们需要format参数,它可以单独使用as.POSIXct转换,而不诉诸strptime/as.POSIXct

my_table[, my_dates := as.POSIXct(my_dates, format = "%m/%d/%Y %H:%M")] 
my_table 
#    my_dates this that 
#1: 2016-12-01 15:30:00 a 1 
#2: 2016-12-01 15:31:00 b 2 
#3: 2016-12-01 15:32:00 c 3 

的原因警告是因为论点as.POSIXct/strptime的顺序。如果我们检查? as.POSIXct,用法

as.POSIXct(X,TZ = “”,...)

这意味着,没有指定format,它认为第二个参数是用于tz

相关问题