How would I generate a random date that has to be between two other given dates?
The function's signature should something like this:
randomDate("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
Here is an answer to the literal meaning of the title rather than the body of this question:
This code is based loosely on the accepted answer.
Just to add another one:
The day handling needs some considerations. With 28 you are on the secure site.
Based on the answer by mouviciel, here is a vectorized solution using numpy. Convert the start and end dates to ints, generate an array of random numbers between them, and convert the whole array back to dates.
The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last lines calculation.
example run:
output:
Here's a solution modified from emyller's approach which returns an array of random dates at any resolution
Part of what's nice about this approach is that
np.datetime64
is really good at coercing things to dates, so you can specify your start/end dates as strings, datetimes, pandas timestamps... pretty much anything will work.