5

I am trying to work out how to return a random time between 2 time ranges. For example, get a random time between 15:00:00 and 22:00:00

So far, I have - but don't know how to limit it

select sec_to_time(floor(15 + (rand() * 86401)))

Any help would be much appreciated!

3 Answers 3

11
SELECT SEC_TO_TIME(
          FLOOR(
             TIME_TO_SEC('15:00:00') + RAND() * (
                  TIME_TO_SEC(TIMEDIFF('22:00:00', '15:00:00'))
             )
          )
        );

Calculate in seconds. Then add a random number that is in the range of seconds between 15:00:00 and 22:00:00 to 15:00:00. Then convert the seconds back to a time value.

  • for more information on the used functions, see this link.
Sign up to request clarification or add additional context in comments.

1 Comment

I know it's been 2.5 years since you posted this answer, but you managed to solve a problem I couldn't figure out on my own. Thanks @fancyPants !
1

Logic is simple,

  1. Get difference between 2 times.
  2. Generate random number between those 2 times(numbers)
  3. You can direct generate time in Minutes or Seconds.

Following is example for getting Random Hour,

select Round((FLOOR(RAND() * (TIME_TO_SEC('15:00:00') - TIME_TO_SEC('22:00:00') + 1)) + TIME_TO_SEC('22:00:00')) / 3600,0)

EDIT : Fiddle

For reference see this link

Comments

1

Try this way

select FROM_UNIXTIME(UNIX_TIMESTAMP('<starting_date_in_date_format>') + FLOOR(0 + (RAND() * UNIX_TIMESTAMP('<ending_date_in_date_format>'))) from dual;

1 Comment

Shouldn't it be select FROM_UNIXTIME(UNIX_TIMESTAMP('<starting_date_in_date_format>') + FLOOR(RAND() * (UNIX_TIMESTAMP('<ending_date_in_date_format>') - UNIX_TIMESTAMP('<starting_date_in_date_format>'))) because rand should be multiplied by distance between unix ending and starting timestamp but not unix ending timestamp itself. Unix timestamp is just an integer so we are basically generating random number from range: range_start + floor(rand() * (range_end - range_start)).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.