1

Have been trying for days to convert a chr column in the format of dd/mm/yyyy HH:MM into dttm in the format of yyyy-mm-dd HH:MM:SS.

nothing works and I keep getting NA as the output as it "failed to pharse"

started with

$ started_at         <chr> "30/5/2021 11:58", "30/5/2021 11:29", "30/5/2021 14:24",~
<br>$ ended_at           <chr> "30/5/2021 12:10", "30/5/2021 12:14", "30/5/2021 14:25",~

entered this

tripdata_202105_processed[['started_at']] <- ymd_hms(tripdata_202105_processed[['started_at']])

and got this

All formats failed to parse. No formats found.
$ started_at NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,~
$ ended_at "30/5/2021 12:10", "30/5/2021 12:14", "30/5/2021 14:25",~

really exhausted whatever i could have do myself, really appreciate any help

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
BenZenoVKa
  • 53
  • 5

1 Answers1

1

The order is day/month/year hour:minute, so we use dmy_hm where d is day, followed by m for month, y for year and h for hour and m for minute

library(lubridate)
dmy_hm(tripdata_202105_processed[['started_at']])

For multiple columns, we can use across

library(dplyr)
tripdata_202105_processed <- tripdata_202105_processed %>%
    mutate(across(c(started_at, ended_at), dmy_hm))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Not sure if you get what im asking for, i wanna change the data type from chr to dttm and the format from dmy HM to ymd HMS – BenZenoVKa May 22 '22 at 17:14
  • @BenZenoVKa yes, i got it. the code converts to POSIXct where the default format is `ymd HMS` i.e. `dmy_hm("30/5/2021 11:58")# [1] "2021-05-30 11:58:00 UTC"` – akrun May 22 '22 at 17:15