0

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.

JackR
  • 165
  • 12
  • I think you should look for `lubridate` package. It is good to parse date in heterogeneous format. – MKR Jan 28 '18 at 22:46

1 Answers1

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"
MKR
  • 19,739
  • 4
  • 23
  • 33