rdatetime

Output gives NA when converting 12-hr to 24-hr time in r


I have a dataframe with a variable I need to convert from 12 hour time to 24 hour time in r so that I can join it to another table. The variable is currently a character vector and here is an example dataframe.

accel_dataT <-
data.frame(
collar_id = c("1305", "1305"),
GMT.Time = c("5/29/2024 1:12:36 PM", "5/29/2024 1:12:38 PM"),
X = c(31, 22))

I need the PM removed and the hour converted from 1 to 13, and "/" marks changed to "-" so that the first GMT.Time in my example dataframe would look like this

5-29-2024 13:12:36

I have tried the following code which worked on a different dataframe in my project where I had to convert from UNIX time.

accel_dataT$GMT.Time <-
as.POSIXct(accel_dataT$GMT.Time, format = "%Y-%m-%d  %H:%M:%OS")

The resulting output is NA values for GMT.Time.

I have also tried other packages. This code did not work...

library(chron)
times(accel_dataT$GMT.Time)

Nor did this...

library(lubridate)
ymd_hms(accel_dataT$GMT.Time)

Solution

  • If you are wanting to do this inside of a mutate statement, this worked for me!

    accel_dataT_date_transformed <- accel_dataT |> 
                      dplyr::mutate(
                           GMT.Time = as.POSIXct(as.character(GMT.Time), format = "%m/%d/%Y %I:%M:%S %p")
                      )  
    

    You can also pull it out of a mutate statement:

    as.POSIXct(as.character(accel_dataT$GMT.Time), format = "%m/%d/%Y %I:%M:%S %p")