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
In python:
(need python
dateutil
library –pip install python-dateutil
)What do you need the random number for? Usually (depending on the language) you can get the number of seconds/milliseconds from the Epoch from a date. So for a randomd date between startDate and endDate you could do:
Pandas + numpy solution
dts is the difference between timestamps in seconds (float). It is then used to create a pandas timedelta between 0 and dts, that is added to the start timestamp.
A tiny version.
Note that both
start
andend
arguments should bedatetime
objects. If you've got strings instead, it's fairly easy to convert. The other answers point to some ways to do so.Since Python 3
timedelta
supports multiplication with floats, so now you can do:given that
start
andend
are of the typedatetime.datetime
. For example, to generate a random datetime within the next day:Conceptually it's quite simple. Depending on which language you're using you will be able to convert those dates into some reference 32 or 64 bit integer, typically representing seconds since epoch (1 January 1970) otherwise known as "Unix time" or milliseconds since some other arbitrary date. Simply generate a random 32 or 64 bit integer between those two values. This should be a one liner in any language.
On some platforms you can generate a time as a double (date is the integer part, time is the fractional part is one implementation). The same principle applies except you're dealing with single or double precision floating point numbers ("floats" or "doubles" in C, Java and other languages). Subtract the difference, multiply by random number (0 <= r <= 1), add to start time and done.