简体   繁体   中英

Converting time to 24 hour of day format in R

I have a data frame that has day of the year, year, month, 12 hr time, and some energy data. I want to make the 12 hr formatted time data into hours of the day (1-24). The time is character class.

format(as.POSIXct(t, format = '%I %p'), format = "%H")

Where

t <- df$time

df$time== time in character class with following format:

"12 a.m." "3 p.m."

but after code I get all NA and no change in column.

I think you should give an example so the result is exactly what you are looking for.. taking a stab at it...

Time2 <− c("11:00 AM", "10:42 AM", "12:34 AM")
format(as.POSIXct(Time2, format = '%I:%M %p'), format = "%H:%M:%S")

Here's a lubridate solution. Assuming that all the times are formatted like your examples: hours only, followed by either "am" or "pm". Date-time conversion functions recognise only "am" or "pm" so you'll need to remove the periods.

library(lubridate) # install first if required

times <- c("12 a.m.", "3 p.m.")

# code with nested functions
new_times <- hour(parse_date_time(gsub("\\.", "", times), "%I %p"))

# code with pipes (easier to read, perhaps)
library(magrittr)
new_times <- times %>% 
  gsub("\\.", "", .) %>% 
  parse_date_time(., "%I %p") %>% 
  hour()

Result:

new_times
[1]  0 15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM