Mysql insert random datetime in a given datetime range

前端 未结 8 1872
迷失自我
迷失自我 2020-11-29 04:59

With SQL , Can I insert random datetime values in a column giving a range?

For example, given a range of 2010-04-30 14:53:27 to 2012-04-30 14:53:2

相关标签:
8条回答
  • 2020-11-29 05:46

    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.

    0 讨论(0)
  • 2020-11-29 05:46

    It's an old thread but still.. In my case I needed to generate random date in format like this : 2017-01-01. If anyone will need it I have used @drew010 solution and formatted date with DATE_FORMAT.

    Here is my code :

    SELECT DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP('2015-01-01') + FLOOR(0 + (RAND() * 63072000))), '%Y-%m-%d');
    
    0 讨论(0)
提交回复
热议问题