Search code examples
rlubridate

Problem parsing my date time in R Lubridate


I am trying to parse my date time by it keep showing me "All formats failed to parse. No formats found."

These are the time I've been trying to parse and the code.

datetime_clean <- c("4:10 pm Sept 18, 2021", "12:06 pm Sept 18, 2021", "9:42 am Sept 18, 2021")

datetime_parse <- parse_date_time(
  datetime_clean, "%I:%M %p %m/%d/%Y" 
)

Solution

  • We may use as.POSIXct from base R. The month is in the format %b but with an extra letter long i.e. %b - denotes to abbreviated month name and it is the first three letter instead of four letter). One option is to remove the 4th letter with sub, and use %b instead of %m

    datetime_clean <- sub("([A-Za-z]{3})[a-z]", "\\1", datetime_clean)
    as.POSIXct(datetime_clean, format = "%I:%M %p  %b %d, %Y")
    

    -output

    [1] "2021-09-18 16:10:00 EDT" "2021-09-18 12:06:00 EDT" "2021-09-18 09:42:00 EDT"
    

    Or with lubridate

    lubridate::parse_date_time(datetime_clean, '%I:%M %p %b %d, %Y')
    

    -output

    [1] "2021-09-18 16:10:00 UTC" "2021-09-18 12:06:00 UTC" "2021-09-18 09:42:00 UTC"
    

    This may also be automatically parsed with parsedate::parse_date (from the original object without the sub modification)

    parsedate::parse_date(datetime_clean)
    [1] "2021-09-18 16:10:00 UTC" "2021-09-18 12:06:00 UTC" "2021-09-18 09:42:00 UTC"
    

    data

    datetime_clean <- c("4:10 pm Sept 18, 2021", "12:06 pm Sept 18, 2021" ,"9:42 am Sept 18, 2021")