您好我有date_time列为"因素"具有如下混合date_time的类型。如何将这些信息更改为R日期时间格式
date_time R_date_time
01-Apr-2017 12:00:00 2017-04-01 12:00:00
02/04/2017 03:00:00 2017-04-02 03:00:00
30/05/2017 06:15:00 2017-05-30 06:15:00
2/4/2017 05:18:00 2017-04-02 05:18:00
2017/12/31 20:30:00 2017-12-31 20:30:00
答案 0 :(得分:0)
您可以使用lubridate
:
> dmy_hms("01-Apr-2017 12:00:00")
[1] "2017-04-01 12:00:00 UTC"
> dmy_hms("02/04/2017 03:00:00")
[1] "2017-04-02 03:00:00 UTC"
> dmy_hms("30/05/2017 06:15:00")
[1] "2017-05-30 06:15:00 UTC"
> ymd_hms("2017/12/31 20:30:00 ")
[1] "2017-12-31 20:30:00 UTC"
> dmy_hms("2/4/2017 05:18:00")#ambiguous format you can use mdy_hms as well
[1] "2017-04-02 05:18:00 UTC"
OR:
> mdy_hms("2/4/2017 05:18:00")
[1] "2017-02-04 05:18:00 UTC"
>ymd_hms("2017/12/31 20:30:00")
[1] "2017-12-31 20:30:00 UTC"
答案 1 :(得分:0)
anytime
包是一个很好的选择。例如:
date_time <- c(text = "01-Apr-2017 12:00:00", "02/04/2017 03:00:00",
"30/05/2017 06:15:00", "2/4/2017 05:18:00", "2017/12/31 20:30:00")
您需要使用addFormats()
添加一些格式,例如:
library(anytime)
anytime::addFormats(c("%d/%m/%Y %H:%M:%S"))
anytime(date_time, tz = "UTC")
[1] "2017-04-01 12:00:00 UTC" "2017-04-02 03:00:00 UTC" "2017-05-30 06:15:00 UTC"
[4] NA "2017-12-31 20:30:00 UTC"
但是,似乎anytime()
无法解析像#34; 2/4/2017 05:18:00&#34;参见例如https://github.com/eddelbuettel/anytime/issues/24。在这种情况下,您可以使用lubridate:dmy_hms("2/4/2017 05:18:00")
或仅使用strptime("2/4/2017 05:18:00", format = "%d/%m/%Y %H:%M:%S", tz = "UTC")