Search code examples
rdplyrtidyverselubridate

Converting three to four digit numeric values to 24-hour format hours:minutes in R


I have the following df (time_df) with one variable (time_numeric).

time_df

time_numeric
<dbl>

840             
850             
900             
910             
920             
930             
940             
950             
1000                
1010    

I want to convert the time_numeric variable to a POSIXct in %H:%M format (e.g., 840 to 08:40, 1730 to 17:30, 2110 to 21:10, etc.).

I searched older posts on Stackoverflow but still needed help to figure it out.

Can you please help?


Solution

  • Basically you need to tack a "0" on any of three digit times and then convert to a POSIXct object with today's date. There are no time only objects.

    times <- c(840, 850, 900, 910, 920,             
           930, 940, 950, 1000, 1010)
    
    times <- ifelse(nchar(times)==3, paste0("0", times), times)
    as.POSIXct(times, "%H%M", tz="EST")