Home > OS >  R change chr to dttm and dateTime format
R change chr to dttm and dateTime format

Time:05-23

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

CodePudding user response:

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))
  •  Tags:  
  • r chr
  • Related