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

标签 r datetime data.table

我的 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/

相关文章:

r - 在 data.table 中使用带有 .SD 的其他列

r - dplyr 重命名不适用于正则表达式

javascript - 使用 knitr 在 R 中为 html 创建条件格式化表

r - 将字符串直接转换为 IDateTime

r - 聚合 data.table 中的列以进行描述性统计

java - 如何以天为单位显示毫秒数 :hours:min:seconds

r - 根据R中的多列对数据框进行排序

c++ - 激活在 R 中运行 libLAS C++ 库

sql - 数据类型为 "timestamp with time zone"的时区存储

php 32 位日期解析 1901 年 12 月 13 日之前的日期