rchron

Create a sequence of times in R?


I want to create a sequence of times 00:00 - 12:00 and 12:00 to 00:00 with 10 minutes step. How can I do this in R?

I have tried with:

library(chron)
t <- merge(0:23, seq(0, 50, by = 10))
chron(time = paste(x$x, ':', x$y), format = c(times = "h:m"))

But I have 2 problems:

  1. I get an error running chron(time = paste(x$x, ':', x$y), format = c(times = "h:m")):

Error in convert.times(times., fmt) : format h:m may be incorrect

  1. How can I turn it to standard time with AM/PM? Should I merge it twice:

t <- merge(0:12, seq(0, 50, by = 10))

t_am <- merge(t, "AM")

t_pm <- merge(t, "PM")

Or maybe another way using POSIXt?


Solution

  • We can use seq :

    format(seq(as.POSIXct('00:00', format = "%H:%M", tz = "UTC"), 
               as.POSIXct(Sys.Date() + 1), by = '10 mins'), "%I:%M%p")
    
    #[1] "12:00AM" "12:10AM" "12:20AM" "12:30AM" "12:40AM" "12:50AM" "01:00AM ...
    #[141] "11:20PM" "11:30PM" "11:40PM" "11:50PM" "12:00AM"
    

    Make sure you have the correct locale or set it via :

    Sys.setlocale("LC_TIME", "en_US.UTF-8")!