Converting to date in a character column that contains two date formats

后端 未结 4 1015

I have CSV file with \"date\" column but it contains two different date format as the following

7/12/2015 15:28 as m/d/yyyy hh:mm
18-04-2016 18:20  as d/m/yy         


        
4条回答
  •  無奈伤痛
    2020-12-06 14:26

    External packages are not required if you simply have two datetime formats. Just run both formats through the parser and take the non-missing one:

    x <- c("7/12/2015 15:28","18-04-2016 18:20")
    pmax(
      as.POSIXct(x, format="%m/%d/%Y %H:%M", tz="UTC"),
      as.POSIXct(x, format="%d-%m-%Y %H:%M", tz="UTC"),
      na.rm=TRUE
    )
    #[1] "2015-07-12 15:28:00 UTC" "2016-04-18 18:20:00 UTC"
    

    As far as I know, there is absolutely no way to deal with ambiguous date formats automatically, so hard-coding is the way to go here probably.

提交回复
热议问题