2

I want to create a single column with a sequence of date/time increasing every hour for one year or one month (for example). I was using a code like this to generate this sequence:

start.date<-"2012-01-15"
start.time<-"00:00:00"
interval<-60 # 60 minutes
increment.mins<-interval*60 
x<-paste(start.date,start.time)

for(i in 1:365){
   print(strptime(x, "%Y-%m-%d %H:%M:%S")+i*increment.mins)
}

However, I am not sure how to specify the range of the sequence of dates and hours. Also, I have been having problems dealing with the first hour "00:00:00"? Not sure what is the best way to specify the length of the date/time sequence for a month, year, etc? Any suggestion will be appreciated.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user1626688
  • 1,583
  • 4
  • 18
  • 27

2 Answers2

12

I would strongly recommend you to use the POSIXct datatype. This way you can use seq without any problems and use those data however you want.

start <- as.POSIXct("2012-01-15")
interval <- 60

end <- start + as.difftime(1, units="days")

seq(from=start, by=interval*60, to=end)

Now you can do whatever you want with your vector of timestamps.

Thilo
  • 8,827
  • 2
  • 35
  • 56
1

Try this. mondate is very clever about advancing by a month. For example, it will advance the last day of Jan to last day of Feb whereas other date/time classes tend to overshoot into Mar. chron does not use time zones so you can't get the time zone bugs that code as you can using POSIXct. Here x is from the question.

library(chron)
library(mondate)

start.time.num <- as.numeric(as.chron(x))

# +1 means one month.  Use +12 if you want one year.
end.time.num <- as.numeric(as.chron(paste(mondate(x)+1, start.time)))

# 1/24 means one hour.  Change as needed.
hours <- as.chron(seq(start.time.num, end.time.num, 1/24))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341