rlubridatemicrosoft-r

Lubridate or ANYTIME to convert from 24hr to 12hr time


As the title suggests, I am trying to use either lubridate or ANYTIME (or similar) to convert a time from 24 hour into 12 hour.. To make life easier I don't need the whole time converted.

What I mean is I have a column of dates in this format:

2021-02-15 16:30:33

I can use inbound$Hour <- hour(inbound$Timestamp) to grab just the hour from the Timestamp which is great.. except that it is still in 24hr time. (this creates an integer column for the hour number)

I have tried several mutates such as inbound <- inbound %>% mutate(Hour = ifelse(Hour > 12, sum(Hour - 12),Hour)

This technically works.. but I get some really wonky values (I get a -294 in several rows for example)..

is there an easier way to get the 12hr time converted?

Per recommendation below I tried to use a base FORMAT as follows:

inbound$Time <- format(inbound$Timestamp, "%H:%M:%S")
inbound$Time <- format(inbound$Time, "%I:%M:%S")

and on the second format I am getting an error

 Error in format.default(inbound$Time, "%I:%M:%S") : 
  invalid 'trim' argument

I did notice the first format converts to a class CHARACTER column.. not sure if that is causing issues with the 2nd format or not..

I then also tried:

 `inbound$time <- format(strptime(inbound$Timestamp, "%H:%M:%S"), "%I:%M %p")`

Which runs without error.. but it creates a full column of NA's

Final edit::::: I made the mistake of mis-reading/applying the solution and that caused errors.. when using the inbound$Time <- format(inbound$Time, "%I:%M:%S") or as.numeric(format(inbound$Timestamp, "%I")) from the comments... both worked and solved the issue I was having.


Solution

  • To be clear... From 2021-02-15 16:30:33 you want just 04:30:33 as a result?

    No need for lubridate or anytime. Assuming that is a Posixct

    
    a <- as.POSIXct("2021-02-15 16:30:33")
    a
    # [1] "2021-02-15 16:30:33 UTC"
    
    b <- format(a, "%H:%M:%S")
    b
    #[1] "16:30:33"
    
    c <- format(a, "%I:%M:%S")
    c
    #[1] "04:30:33"