问题
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