SQLite - select random datetime in range
The random()
function generates random 64-bit integers.
The strftime()
function with the '%s'
parameter converts a date/time string into the number of seconds since 1970.
The datetime()
function with the 'unixepoch'
modifier converts a number of seconds into a date/time string.
To convert the random integer into the desired range of seconds, use the modulo operator (%
) with the difference in seconds between the min/max dates as range, and add that to the start date.For example, the following will generate a random timestamp in Jan 2000:
SELECT datetime(strftime('%s', '2000-01-01 00:00:00') + abs(random() % (strftime('%s', '2000-01-31 23:59:59') - strftime('%s', '2000-01-01 00:00:00')) ), 'unixepoch');