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
Use ApacheCommonUtils to generate a random long within a given range, and then create Date out of that long.
Example:
import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;
public Date nextDate(Date min, Date max) {
}
Updated answer
It's even more simple using Faker.
Installation
Usage:
Old answer
It's very simple using radar
Installation
Usage
To chip in a pandas-based solution I use:
I like it, because of the nice
pd.Timestamp
features that allow me to throw different stuff and formats at it. Consider the following few examples...Your signature.
Random position.
Different format.
Passing pandas/datetime objects directly.
It's modified method of @(Tom Alsberg). I modified it to get date with milliseconds.
Example:
Output:
2028/07/08 12:34:49.977963
Many algorithms for converting date to and from numbers are already available in many operating systems.
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
0
padding - blame the American time format conventions):