r语言 - 如何在不使用 strptime 的情况下转换 data.table 中不明确的日期时间列



My data.table 有一列的日期时间格式为"不明确":"12/1/2016 15:30"。如何将此日期时间转换为 R 在 data.table 中识别的格式,而无需使用 strptime() 并收到最初转换为 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,用法是

如。POSIXct(x, tz = ", ...)

这意味着,在没有指定format的情况下,它认为第二个参数是tz

最新更新