Character to Date Time Conversion R (with AM/PM)

75 Views Asked by At

I need to convert a character class to a date time. The character format looks like this

1/3/2023 6:16am

I've tried a few things with little success. Ultimately, I would like to have the date and time in separate columns in the data frame.

The data frame looks something like this:

ID work_type date
1 A 1/3/2023 6:16am
2 B 1/3/2023 6:20am
3 A 1/4/2023 6:18am

I need it to be separate and have the correct classes like the following

ID work_type date time
1 A 1/3/2023 6:16am
2 B 1/3/2023 6:20am
3 A 1/4/2023 6:18am
2

There are 2 best solutions below

0
akrun On

We could do

library(tidyr)
separate_wider_delim(df1, date, delim = " ", names = c("date", "time"))

-output

# A tibble: 3 × 4
     ID work_type date     time  
  <int> <chr>     <chr>    <chr> 
1     1 A         1/3/2023 6:16am
2     2 B         1/3/2023 6:20am
3     3 A         1/4/2023 6:18am

If we want the classes to be modified

library(parsedate)
library(data.table)
df1 %>% 
   mutate(datetime = parse_date(date)) %>% 
   mutate(date = as.Date(datetime), time = as.ITime(datetime),
    .keep = "unused")

-output

ID work_type       date     time
1  1         A 2023-01-03 06:16:00
2  2         B 2023-01-03 06:20:00
3  3         A 2023-01-04 06:18:00

data

df1 <- structure(list(ID = 1:3, work_type = c("A", "B", "A"),
 date = c("1/3/2023 6:16am", 
"1/3/2023 6:20am", "1/4/2023 6:18am")), class = "data.frame", row.names = c(NA, 
-3L))
0
amanwebb On

I would do something like this

df[c('Date', 'Time')] <- str_split_fixed(df$date, ' ', 2)

df$date <- lapply(df$date, function(x) as.Date(x, format = '%m/%d/%Y'))
df$date <- unlist(df$date)

df$time <- lapply(df$time, function(x) as.POSIXlt(x, format = '%I:%M%p'))
df$time <- unlist(df$time)