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.
CodePudding user response:
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")
CodePudding user response:
Here's a lubridate
solution. Assuming that all the times are formatted like your examples: hours only, followed by either "a.m." or "p.m.". 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