runjumpfly runjumpfly - 1 year ago 65
R Question

Creating time index that creates same intervals every day

I want to make a time index that starts at 9:15:00 and progress in 50-minute intervals before ending at 03:30:00. E.g. 9:15:00,10:05:00, 10:55:00 and so on. This is my code that perfectly creates these time indices for 1st day. However, it becomes messed up next day and begins at 09:25:00 instead of 09:15:00 and gets all intervals wrong. The start time keeps changing every day.

Intervals <- seq(as.POSIXct("2016-04-01 09:15:00", format="%Y-%m-%d %H:%M:%S"), as.POSIXct("2016-04-29 15:30:00", format="%Y-%m-%d %H:%M:%S"),
by="50 min")

As I am trying to calculate various intervals by change only argument
by="50 min"
for example to
by="55 min"
and need flexibility in fixing the end time, so I put it as before 15:30:00 . Please me to fix It?

Answer Source

You might be better off generating one sequence and reusing this for each day. As so:

start <- "2016-04-01"
stop  <- "2016-04-29"
daylength <- difftime(as.POSIXct(stop), as.POSIXct(start), units="days")

Intervals <- seq(
  as.POSIXct(paste(start, "09:15")),
  as.POSIXct(paste(start, "15:30")),
  by="50 min"

out <- Intervals + as.difftime(rep(0:daylength, each=length(Intervals)), units="days")
#[1] "2016-04-01 09:15:00 AEST" "2016-04-29 15:05:00 AEST"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download