0

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.

neilfws
  • 32,751
  • 5
  • 50
  • 63
JLG_10
  • 1
  • 1
  • 2
    Please read about [how to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and update your question accordingly. Include a sample of your data by pasting the output of `dput()` into your post or `dput(head())` if you have a large data frame. Also include code you have tried and any relevant errors. If you cannot post your data then please post code for creating a representative data set. – LMc May 11 '22 at 21:28
  • Are all of the times hours only, as in your example, or do some have minutes? – neilfws May 11 '22 at 22:36
  • @neilfws there are no minutes – JLG_10 May 11 '22 at 22:49

2 Answers2

0

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")
Martin Gal
  • 16,640
  • 5
  • 21
  • 39
  • Hello. The column I am trying to change is a character class with the following format "12 a.m." I was able to make hour to work so get 12 for 12 a.m. but I also got 12 for 12 p.m. I am trying to use the column of time to get hour of day in 24 hr format. BA.Code date time Demand..MWh. doy year [1,] "AZPS" "6/19/2017" "12 a.m. " "4494" "170" "2017" [2,] "AZPS" "6/19/2017" "1 a.m. " "4118" "170" "2017" [3,] "AZPS" "6/19/2017" "2 a.m. " "3840" "170" "2017" " – JLG_10 May 11 '22 at 21:37
  • I used format 'format(as.POSIXct(t,format='%I %p'),format="%H")' and t=df$time column but nothing changes and it comes back as NA – JLG_10 May 11 '22 at 21:45
0

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
neilfws
  • 32,751
  • 5
  • 50
  • 63