Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R convert string to time

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.

like image 537
Tracy Avatar asked Sep 29 '25 09:09

Tracy


1 Answers

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.

like image 186
detroyejr Avatar answered Oct 02 '25 04:10

detroyejr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!