Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

r - Convert 12hour time to 24Hour time

I have hourly weather data. I've seen the function examples from here: http://casoilresource.lawr.ucdavis.edu/drupal/node/991

I'm altering the code to account for airport data, which has a different URL type. Another issue with the airport weather data is that the time data is saved in 12 hour format. Here is a sample of the 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's what I attempted: (I see that using just 'PM' isn't careful enough because any times between 12 and 1 pm will be 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Would strptime work?

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 in case you don't want the date, something like: Although it depends what kind of class would you want for the object.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...