I have the following set of times data, that I have to convert into 12 hour format.
-----------------
814
830
1835
1730
1442
820
1430
930
1550
1725
1615
1010
You can try,
format(strptime(substr(as.POSIXct(sprintf("%04.0f", x),
format="%H%M"), 12, 16), '%H:%M'), '%I:%M %p')
#[1] "08:14 AM" "08:30 AM" "06:35 PM" "05:30 PM" "02:42 PM" "08:20 AM"
data
x <- c(814, 830, 1835, 1730,1442, 820)
This should work:
myMtime #time vector
myMtime <- sprintf("%04d", myMtime)
myStdTime <- as.POSIXct(myMtime, format = "%H%M", origin = "1970-01-01", tz = "UTC")
myStdTime #time as unix standard for time zone UTC
Note that R will automatically add the year-month-day of the day you are converting myMtime
. If you want to add a specific date, do the following:
myMtime #time vector
date <- "2016-01-01"
myMtime <- sprintf("%04d", myMtime)
myStdTime <- as.POSIXct(paste0(date, " ", myMtime), format = "%Y-%m-%d %H%M", origin = "1970-01-01", tz = "UTC")
myStdTime #time as unix standard for time zone UTC
For the output format use format
:
format(myStdTime, format = "%r%p")
#or thing like that:
format(myStdTime, format = "%a %b %d %X %Y %Z")
#for further explanations consider:
?strptime