简体   繁体   中英

R change chr to dttm and dateTime format

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM