Convert time from 12 hours to 24 hours

I have weather data. I saw examples of functions here: http://casoilresource.lawr.ucdavis.edu/drupal/node/991

I am changing the code for accounting for airport data, which has a different type of URL. Another problem with airport meteorological data is that time data is stored in a 12-hour format. Here is sample data:

14 10:43 AM 15 10:54 AM 16 11:54 AM 17 12:07 PM 18 12:15 PM 19 12:54 PM 20 1:54 PM 21 2:54 PM 

Here I tried: (I see that using only "PM" is not thorough enough, because any time between 12 and 1 hours will be turned off if they go through this alg)

 date<-Sys.Date() data$TimeEST<-strsplit(data$TimeEST, ' ') for (x in 1:35){ if('AM' %in% data$TimeEST[[x]]){ gsub('AM','',data$TimeEST[[x]]) data$TimeEST[[x]]<-str_trim(data$TimeEST[[x]]) data$TimeEST[[x]]<-str_c(date,' ',data$TimeEST[x],':',data$TimeEST[2]) } else if('PM' %in% data$TimeEST[[x]]){ data$TimeEST[[x]]<-gsub('PM', '',data$TimeEST[[x]]) data$TimeEST[[x]]<-strsplit(data$TimeEST[[x]], ':') data$TimeEST[[x]][[1]][1]<-as.integer(data$TimeEST[[x]][[1]][1])+12 data$TimeEST[[x]]<-str_trim(data$TimeEST[[x]][[1]]) data$TimeEST[[x]]<-str_c(date, " ", data$TimeEST[[x]][1],':',data$TimeEST[[x]][2]) } } 

Any help?

+7
source share
2 answers

Does strptime ?

 df2= structure(c("10:43 AM", "10:54 AM", "11:54 AM", "12:07 PM", "12:15 PM", "12:54 PM", "1:54 PM", "2:54 PM"), .Dim = c(8L, 1L)) strptime(df2, "%I:%M %p" ) 

Or, if you do not need a date, something like: Although it depends on what class you need for the object.

 substr(strptime(df2, "%I:%M %p" ),11,19) 
+15
source

take a look at ?strptime .

 as.POSIXct(data$TimeEST, format='%I:%M %p') 
+3
source

All Articles