Convert to 12 hour format using lubridate

Hi everyone,

When using the mdy_hms function, I get the results in 24 hour format. Is there a way that I could change it to 12 hour one as the original was written in AM/PM method.

Thanks :slightly_smiling_face: :slightly_smiling_face:

Given how vibrant the R universe is, I am sure there is a package that implements what you are looking for. You should keep looking. However, what I bring to you is a solution in base R:

# The time now (which should be similar to the output of your call to lubridate::mdy_hms()
d <- Sys.time()
d
[1] "2022-03-13 00:50:10 CST"

 # Extract the time
time_string <- format(d, "%H:%M:%S")

# Convert the time to AM/PM format
format(strptime(time_string, "%H:%M:%S"), "%I:%M %p") 
[1] "12:50 AM"

Finally, you can extract the date from d and paste the AM/PM time to it.

Here is a function which combines all the steps above for you. x is the result of your call to lubridate::mdy_hms():

mdy_hms2 <- function(x){
  
  date_string <- format(x, "%Y-%m-%d")  
  time_string <- format(x, "%H:%M:%S")
  time_string2 <- strptime(time_string, format = "%H:%M:%S") |>
    format("%I:%M %p")
  
  paste(date_string, time_string2)
  
}

d <- mdy_hms("03-12-2022 19:17:51")
mdy_hms2(d)
[1] "2022-03-12 07:17 PM"
1 Like

Many thanks for your help Ghislain. I'll try both for sure :+1: :+1:

edit_1:
I've tried and it works perfect but it converts the data type into character again.

I'm glad I could help.

Hum, I'm not sure how to convert the new format as date_time again. R's default is the 24-hour format. If your dates are in a data frame, maybe you could have two date columns? One for the 24-hour date format and another one for the 12-hour date format.

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.