Manage multiple Date formats to POSIXct [duplicate]

為{幸葍}努か 提交于 2020-01-11 13:28:11

问题


I have two dataframe with two different format of date the first is "%d/%m/%Y %H:%M:%S" and the second "%Y-%m-%d %H:%M:%S".

I want to create a function that convert to POSIXct by indicating the format.

My code:

date_func <- function(df){
 colnum <- grep("DATE", colnames(df))
 df[, (colnum) := lapply(.SD, dmy_hms), .SDcols = colnum]
 return(df)
}

For the first format it's works but for the second I have only NA values after the conversion.

So, how can I create a function that convert to POSIXct whatever the indicated format?

Thanks for your help.


回答1:


Package lubridate provides very good option to handle date/time in heterogeneous format. The parse_date_time can be used. A simple example on converting date/time in format specified in OP are:

library(lubridate)
>parse_date_time(c("01/12/2016 01:11:54", "2015-12-31 10:05:11"), c("dmY HMS", "Ymd HMS"))
# [1] "2016-12-01 01:11:54 UTC" "2015-12-31 10:05:11 UTC"


来源:https://stackoverflow.com/questions/48492156/manage-multiple-date-formats-to-posixct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!