Mysql insert random datetime in a given datetime range
Solution 1:
Here is an example that should help:
INSERT INTO `sometable` VALUES(
FROM_UNIXTIME(
UNIX_TIMESTAMP('2010-04-30 14:53:27') + FLOOR(0 + (RAND() * 63072000))
)
)
It uses the date 2010-04-30 14:53:27
as the base, converts that to a Unix timestamp, and adds a random number of seconds from 0 to +2 years to the base date and converts it back to a DATETIME.
It should be pretty close but over longer time periods leap years and other adjustments will throw it off.
Solution 2:
This should work nicely:
SET @MIN = '2010-04-30 14:53:27';
SET @MAX = '2012-04-30 14:53:27';
SELECT TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, @MIN, @MAX)), @MIN);
TIMESTAMPDIFF
is used to determine the number of seconds in the date range. Multiply this by a random number between 0-1 results in a random number between 0 and the number of seconds in the range. Adding this random number of seconds to the lower bound of the range results in a random date between the data range bounds.
Solution 3:
This works perfectly even for leap years:
select from_unixtime(
unix_timestamp('2000-1-1') + floor(
rand() * (
unix_timestamp('2010-12-31') - unix_timestamp('2000-1-1') + 1
)
)
)
The idea is simple: Just take a random timestamp between the two timestamps, then convert it to a datetime
using from_unixtime
. This way you can ensure that each option has equal probability.