Reformatting time strings

I have a data frame (imported from CSV) containing columns of time, in 24 hour format with no punctuation (e.g., "803" or "1335"). I would like to reformat them to a 12 hour format (e.g., "8:03 AM" and "1:35 PM"). I know how to do this with x |> strptime(format = "%H:%M") |> strftime(format = "%I:%M:%S %p") if the initial string x contains a colon (which mine do not). My preference would be to avoid jumping through hoops with nchar and substring just to insert the bleeping colon. So does anyone know an elegant way to make the conversion starting from the original strings or, if not, an elegant/efficient way to insert the colon before the final two characters in the original string?

Is using str_replace acceptable?

library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 4.3.3
DF <- data.frame(TIME = c("803", "1335", "003","1019"),
                 NUM = 1:4)
DF |> mutate(TIME = str_replace(TIME, "(.+)(\\d\\d$)", "\\1:\\2"))
#>    TIME NUM
#> 1  8:03   1
#> 2 13:35   2
#> 3  0:03   3
#> 4 10:19   4

Created on 2024-07-22 with reprex v2.0.2

1 Like
library(lubridate)
parse_date_time(1335, orders  = 'HM') |> 
  strftime(format = '%I:%M %p', tz =  'UTC')
#> [1] "01:35 PM"

Created on 2024-07-22 with reprex v2.0.2

2 Likes

you can use your original code; just omit the colon on your strptime format.

"1335" |> strptime(format = "%H%M") |> strftime(format = "%I:%M:%S %p")
1 Like

Thanks. That almost works, the catch being that I would need to add a leading 0 to morning times. It works with "0803" but throws NA with "803".

Thanks. This one also requires the time to have a leading zero if in the morning (which in turn requires it to be a string, which is fine). Both 803 and "803" throw NAs.

Thanks! I thought of using regex, but my regex skills are a bit lacking.

How about this, then?

library(stringr)
library(lubridate)
str_pad(803, 4, pad = 0) |> 
  parse_date_time(orders = 'HM') |> 
  strftime(format = '%I:%M %p', tz = 'UTC')
#> [1] "08:03 AM"

Created on 2024-07-23 with reprex v2.0.2

2 Likes

Yes, that works nicely.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.