How would I generate a random date that has to be between two other given dates?
The function’s signature should be something like this:
random_date('1/1/2008 1:30 PM', '1/1/2009 4:50 AM', 0.34) ^ ^ ^ date generated has date generated has a random number to be after this to be before this
and would return a date such as: 2/4/2008 7:20 PM
Convert both strings to timestamps (in your chosen resolution, e.g. milliseconds, seconds, hours, days, whatever), subtract the earlier from the later, multiply your random number (assuming it is distributed in the
range [0, 1]) with that difference, and add again to the earlier one. Convert the timestamp back to date string and you have a random time in that range.Python example (output is almost in the format you specified, other than
0padding – blame the American time format conventions):