Convert datetime to 12hr format, while still keeping the date in R

Viewed 33
        date                    Time
1     2022-08-28 12:00:00       80.9 
2     2022-08-28 13:00:00       81.6   
3     2022-08-28 14:00:00       81.2
4     2022-08-28 15:00:00       81.4
5     2022-08-28 16:00:00       89.0    

Every solution I've seen gets rid of the date and keeps the time. However, I would like to convert the date column to 12 hr format while still keeping the date intact. If possible, I'd like to ensure the column is still a POSIXct data type after conversion as well.

1 Answers
(t1 <- Sys.time())
# [1] "2022-09-02 21:28:36 CST"
class(t1)
# [1] "POSIXct" "POSIXt"

(t2 <- strftime(t1, '%F %r'))
# [1] "2022-09-02 09:28:36 PM"
class(t2)
# [1] "character"

Back to POSIXct:

(t3 <- as.POSIXct(t2, format = '%F %r')) # or strptime(t2, '%F %r')
# [1] "2022-09-02 21:28:36 CST"
class(t3)
# [1] "POSIXct" "POSIXt"
Related