1

How to sample the time between the specified range (08:00:00 to 15:00:00). Please help!

Code I tried, but raises error

sample(seq(as.Date.POSIXct('08:00:00'), as.Date.POSIXct('15:00:00')), 20)

Expected:

[1] "08:01:00" "14:00:50" "12:49:50"  
prog
  • 1,073
  • 5
  • 17
  • 1
    It's `as.Date.POSIXct()` causing the error, not `sample()`. – neilfws Sep 12 '19 at 01:04
  • 1
    Very related (possible duplicate) - [efficiently generate a random sample of times and dates between two dates](https://stackoverflow.com/questions/14720983/efficiently-generate-a-random-sample-of-times-and-dates-between-two-dates) – thelatemail Sep 12 '19 at 01:17

1 Answers1

2

Create sequence of times within the specific duration and sample. The time would have todays date, to get only time component we use format.

all_times <- format(seq(as.POSIXct('08:00:00', format = "%T"), 
                         as.POSIXct('15:00:00', format = "%T"), by = "sec"), "%T")

sample(all_times, 3)  
#[1] "11:51:16" "09:50:10" "13:09:21"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213