Tracy
Tracy

Reputation: 709

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.

Upvotes: 3

Views: 5722

Answers (3)

akrun
akrun

Reputation: 887851

We could also use the lubridate functions to parse the format after pasteing the date

library(lubridate)
library(glue)
ymd_hm(glue("2018-01-01 {time}M"))
#[1] "2018-01-01 11:10:00 UTC" "2018-01-01 23:20:00 UTC"
#[3] "2018-01-01 16:20:00 UTC" "2018-01-01 14:45:00 UTC"

Upvotes: 2

Mike H.
Mike H.

Reputation: 14370

In your question, you say that you want to be able to subtract these times. I think it makes the most sense to convert it to a POSIXct object. If you want a specific day/month/year you need to append it to your string like below, otherwise you can not specify one and it will assume the date is today:

date2 = as.POSIXct(paste0("01-01-2018 ", time, "m"), format = "%m-%d-%Y %I%M%p")

date2
#[1] "2018-01-01 11:10:00 EST" "2018-01-01 23:20:00 EST" "2018-01-01 16:20:00 EST" "2018-01-01 14:45:00 EST"

Upvotes: 1

detroyejr
detroyejr

Reputation: 1154

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.

Upvotes: 5

Related Questions