我的 data.table 有一列“不明确”的日期时间格式:“12/1/2016 15:30”。如何在不使用 strptime()
的情况下将此日期时间转换为 R 在 data.table 中识别的格式并获取初始转换为 POSIXlt 的警告消息。该过程有效,但警告让我认为还有另一种方法。
我的数据表:
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")]
并且时间也被丢弃并且警告被退回。谢谢你的建议。
最佳答案
我们需要 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
关于r - 如何在不使用 strptime 的情况下转换 data.table 中不明确的日期时间列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41511617/