user9605051
user9605051

Reputation: 61

Converting 12 hours to 24 hours in R

How do we convert a vector of 12 hour character into 24 hours? For example, lets say I have a vector

v = c('9AM','10AM','1PM','5PM')

and I'm trying to get an output of 9, 10, 13, 17 based on AM/PM and appending AM/PM.

Upvotes: 5

Views: 855

Answers (1)

rafaelc
rafaelc

Reputation: 59284

>>> v = c('9AM','10AM','1PM','5PM')
>>> times = strptime(v, "%I%p")


[1] "2018-04-06 09:00:00 GMT" "2018-04-06 10:00:00 GMT" "2018-04-06 13:00:00 GMT" "2018-04-06 17:00:00 GMT"

If you just need the hour

>>> times$hour #as commented by @thelatemail

[1] 9 10 13 17

or

>>> library(lubridate)
>>> hour(times)

[1] 9 10 13 17

Upvotes: 6

Related Questions