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

Time:09-03

        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.

CodePudding user response:

(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"

CodePudding user response:

format(as.POSIXct(dat$date), format = "%Y-%M-%d %I:%M:%S %p")
#[1] "2022-00-28 12:00:00 PM" "2022-00-28 01:00:00 PM" "2022-00-28 02:00:00 PM" "2022-00-28 03:00:00 PM" "2022-00-28 04:00:00 PM"

#or
#format(as.POSIXct(dat$date), format = "%F %r")
  • Related