Bruh
Bruh

Reputation: 285

Converting character to dates with hours and minutes

I'm having trouble converting character values into date (hour + minutes), I have the following codes:

start <- c("2022-01-10 9:35PM","2022-01-10 10:35PM")
end <- c("2022-01-11 7:00AM","2022-01-11 8:00AM")
dat <- data.frame(start,end)

These are all in character form. I would like to:

  1. Convert all the datetimes into date format and into 24hr format like: "2022-01-10 9:35PM" into "2022-01-10 21:35", and "2022-01-11 7:00AM" into "2022-01-11 7:00" because I would like to calculate the difference between the dates in hrs.
  2. Also I would like to add an ID column with a specific ID, the desired data would like this:
ID <- c(101,101)
start <- c("2022-01-10 21:35","2022-01-10 22:35")
end <- c("2022-01-11 7:00","2022-01-11 8:00")
diff <- c(9,10) # I'm not sure how the calculations would turn out to be 
dat <- data.frame(ID,start,end,diff)

I would appreciate all the help there is! Thanks!!!

Upvotes: 0

Views: 248

Answers (1)

Ma&#235;l
Ma&#235;l

Reputation: 51994

You can use lubridate::ymd_hm. Don't use floor if you want the exact value.

library(dplyr)
library(lubridate)
dat %>% 
  mutate(ID = 101,
         across(c(start, end), ymd_hm),
         diff = floor(end - start))

                start                 end  ID    diff
1 2022-01-10 21:35:00 2022-01-11 07:00:00 101 9 hours
2 2022-01-10 22:35:00 2022-01-11 08:00:00 101 9 hours

The base R approach with strptime is:

strptime(dat$start, "%Y-%m-%d %H:%M %p")
[1] "2022-01-10 09:35:00 CET" "2022-01-10 10:35:00 CET"

Upvotes: 3

Related Questions