Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 12 hours to 24 hours in R

Tags:

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.

like image 682
user9605051 Avatar asked Apr 06 '18 00:04

user9605051


1 Answers

>>> 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
like image 198
rafaelc Avatar answered Oct 03 '22 03:10

rafaelc