如何在不使用strptime的情况下转换data.table中不明确的datetime列? [英] How to convert an ambiguous datetime column in data.table without using strptime?

查看:40
本文介绍了如何在不使用strptime的情况下转换data.table中不明确的datetime列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的data.table有一列,其日期时间格式为模棱两可":"12/1/2016 15:30".如何在不使用 strptime()的情况下,将该日期时间转换为R在data.table中识别的格式,并获得警告消息,以便最初转换为POSIXlt.该过程有效,但警告使我认为还有另一种方法.

My data.table has a column with an "ambiguous" datetime format: "12/1/2016 15:30". How can I convert this datetime to a format R recognizes in a data.table without using strptime() and getting the warning message for initially converting to POSIXlt. The process works but the warning makes me think there is another way.

我的数据表:

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 [,date:= as.POSIXct(dates)] ,但是这删除了datetime的时间部分.我也尝试过 my_table [,date:= as.POSIXct(dates,%m/%d/%Y%H:%M")] ,并且时间也减少了,并且警告退缩了.

So, it works but I bet there is a technique that I have simply overlooked to avoid this warning. I used my_table[, dates:= as.POSIXct(dates)] but this drops the time portion of the datetime. I have also tried my_table[, dates:= as.POSIXct(dates, "%m/%d/%Y %H:%M")] and the time is dropped as well and warnings are retruned.

谢谢你的建议.

推荐答案

我们需要 format 参数,并且可以单独使用 as.POSIXct 进行转换,而无需诉诸 strptime/as.POSIXct

We need the format argument and it can be converted using as.POSIXct alone without resorting to 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 ,则用法是

The reason for the warning is because of the order of arguments in as.POSIXct/strptime. If we check ?as.POSIXct, the usage is

as.POSIXct(x,tz =",...)

as.POSIXct(x, tz = "", ...)

这意味着,在未指定 format 的情况下,它认为第二个参数用于 tz

That means, without specifying the format, it thinks that the second argument is for tz

这篇关于如何在不使用strptime的情况下转换data.table中不明确的datetime列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆