Sebastian Zeki
Sebastian Zeki

Reputation: 6874

Generate random times in sample of POSIXct

I want to generate a load of POSIXct dates. I want to have the time component only between 9am and 5pm and only at 15 minute blocks. I know how to generate the random POSIXct between certain dates but how do I specify the minute blocks and the time range. This is where I am at:

sample(seq(as.POSIXct('2013/01/01'), as.POSIXct('2017/05/01'), by="day"), 1000)

Upvotes: 4

Views: 1842

Answers (3)

loki
loki

Reputation: 10350

As @AEF also pointed out, you can use the argument by to create the sequence in steps of 15 minutes.

x <- seq(as.POSIXct('2013/01/01'), as.POSIXct('2017/05/01'), by="15 mins")

You then can use lubridate::hour() like this to extract the values from the sequence and create the sample:

library(lubridate)
sample(x[hour(x) > "09:00" & hour(x) < "17:00"], 1000)
# [1] "2015-06-28 12:45:00 CEST" "2014-05-04 10:15:00 CEST" "2017-01-08 01:00:00 CET"  "2015-06-22 12:30:00 CEST"
# [5] "2016-01-14 13:30:00 CET"  "2015-06-15 14:00:00 CEST" "2014-11-20 13:15:00 CET"  "2013-09-23 11:15:00 CEST"
# [9] "2014-11-25 11:30:00 CET"  "2014-12-04 15:30:00 CET"  "2016-05-28 14:45:00 CEST" "2017-01-12 14:15:00 CET" 
# .....

Upvotes: 2

Sebastian Zeki
Sebastian Zeki

Reputation: 6874

OK so I used this in the end:

ApptDate<-sample(seq(as.Date('2013/01/01'), as.Date('2017/05/01'), by="day"), 1000)
Time<-paste(sample(9:15,1000,replace=T),":",sample(seq(0,59,by=15),1000,replace=T),sep="")             
FinalPOSIXDate<-as.POSIXct(paste(ApptDate," ",Time,sep=""))

Upvotes: 0

AEF
AEF

Reputation: 5650

Just change the by argument to 15mins:

sample(seq(as.POSIXct('2013/01/01'), as.POSIXct('2017/05/01'), by="15 mins"), 1000)

EDIT: I overlooked that the time component should be between 9am and 5pm. To take this into account I would filter the sequence:

library(lubridate)
possible_dates <- seq(as.POSIXct('2013/01/01'), as.POSIXct('2017/05/01'), by="15 mins")
possible_dates <- possible_dates[hour(possible_dates) < 17 & hour(possible_dates) >=9]
sample(possible_dates, 1000)

Upvotes: 8

Related Questions