I would like to convert a string to time. I have a time field where the string has only four digits and a letter (A or P). There is no colon between the digits showing it is a time. I would like to convert the string, which is 12 hours, to a 24 hour time so I can drop the A and P.
Here is an example:
time = c("1110A", "1120P", "0420P", "0245P")
I'm looking for a time class that loos like this:
Answer= c('11:10', '23:20', '16:20', '14:45')
Any help would be greatly appreciated.
You can use the function strptime
to create dates from strings after making one small change to your strings.
time <- c("1110A", "1120P", "0420P", "02:45P")
time <- gsub(":", "", time)
time <- strptime(x = paste0(time, "m"), format = "%I%M%p")
paste
is needed for strptime
to parse with the format that we've given it. %I
is an hour (00-24), %M
is the minute and %p
is for parsing AM/PM.
Once it's parsed as a date, you can use format for pretty printing, or use the normal operators on it like +
, -
, diff
, etc....
strptime
gives you a lot of flexibility when parsing dates, but sometimes you have to try a few things when dates are not in a standard format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With