zhaoy
zhaoy

Reputation: 442

convert 24-hour time to 12-hour time

I have a 2-column data-frame named bc:

time      bc
14:56:00  NA
14:57:00  -76
14:58:00  1301
14:59:00  1057
15:00:00  -336
15:01:00  490

I attempted to convert the time variable from 24-hour time to 12-hour time with the following code:

bc$time <- strptime(x = bc$time,
                    format = "%I:%M:%S",
                    tz = "")

I received the following error message:

"Error in seq.int(0, to0 - from, by): "to" cannot be NA, NaN or infinite

Calls: ... pretty.POSIXt -> prettyDate -> calcSteps -> seq -> seq.POSIXt

Execution halted"

I searched for answers on StackOverflow, but only found answers for converting from 12-hour time to 24-hour time, which is the opposite of my goal.

I appreciate any insight.

Upvotes: 5

Views: 5883

Answers (1)

akrun
akrun

Reputation: 887881

As mentioned by @Pascal, use %H:%M:%S in the format of strptime and then use %I:%M:%S to convert to 12-hour time. We can add %p to denote the 'AM/PM'

format(strptime(bc$time, format='%H:%M:%S'), '%I:%M:%S %p')
#[1] "02:56:00 PM" "02:57:00 PM" "02:58:00 PM" "02:59:00 PM" "03:00:00 PM"
#[6] "03:01:00 PM"

According to ?strptime, %r can replace the %I:%M:%S %p

format(strptime(bc$time, format='%H:%M:%S'), '%r')
#[1] "02:56:00 PM" "02:57:00 PM" "02:58:00 PM" "02:59:00 PM" "03:00:00 PM"
#[6] "03:01:00 PM"

data

bc <- structure(list(time = c("14:56:00", "14:57:00", "14:58:00",
"14:59:00", 
"15:00:00", "15:01:00"), bc = c(NA, -76L, 1301L, 1057L, -336L, 
490L)), .Names = c("time", "bc"), class = "data.frame", 
row.names = c(NA, -6L))

Upvotes: 11

Related Questions