How to convert a column of a dataset from character to datetime (format= MM/DD/YYYY HH:MM:SS)?

Is there a way to change the data type without having to create a new variable?
Or, how do I include the new variable in the same data set in place of the column with the wrong data type?

Rows: 500
Columns: 13
$ ride_id            <chr> "751A27255D582C86", "AC6F9CCE91DABD65", "A753204E7AEA3A4C", "7C43B01CA2345551", "19B63A309…
$ rideable_type      <chr> "electric_bike", "electric_bike", "electric_bike", "electric_bike", "electric_bike", "elec…
$ started_at         <chr> "1/3/2022 14:09:10", "1/2/2022 3:46:40", "1/1/2022 10:43:38", "1/3/2022 14:58:45", "1/16/2…
$ ended_at           <chr> "1/3/2022 14:24:15", "1/2/2022 4:05:41", "1/1/2022 10:46:54", "1/3/2022 15:00:01", "1/16/2…
$ start_station_name <lgl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA…
$ start_station_id   <lgl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA…
$ end_station_name   <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA…
$ end_station_id     <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA…
$ start_lat          <dbl> 42.01, 41.97, 42.01, 42.00, 42.01, 42.00, 42.00, 42.01, 42.01, 42.00, 42.00, 42.00, 41.99,…
$ start_lng          <dbl> -87.71, -87.70, -87.69, -87.67, -87.70, -87.69, -87.66, -87.67, -87.71, -87.67, -87.68, -8…
$ end_lat            <dbl> 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42…
$ end_lng            <dbl> -87.68, -87.68, -87.69, -87.67, -87.69, -87.69, -87.66, -87.66, -87.71, -87.70, -87.68, -8…
$ member_casual      <chr> "casual", "casual", "member", "member", "member", "member", "member", "member", "member", …

The as_datetime() function from the lubridate package should work for you.

x <- "01/01/2023 12:01:01"
as_datetime(x,format="%m/%d/%Y %H:%M:%S")

So, for your example, if your dataset is named data.

data$started_at <- as_datetime(data$started_at,format="%m/%d/%Y %H:%M:%S")
data$ended_at <- as_datetime(data$ended_at,format="%m/%d/%Y %H:%M:%S")

You can specify your timezone using the tz argument.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.