How could a sequence of random dates be generated, given year interval?
With date
, shuf
and xargs
:
Convert start and end date to "seconds since 1970-01-01 00:00:00 UTC" and use shuf
to print six random values in this range. Pipe this result to xargs
and convert the values to the desired date format.
Edit: If you want dates of the year 2017 to be included in the output, you have add one year -1s (2017-12-31 23:59:59
) to the end date. shuf -i
generates random numbers including start and end.
shuf -n6 -i$(date -d '1987-01-01' '+%s')-$(date -d '2017-01-01' '+%s')\
| xargs -I{} date -d '@{}' '+%d/%m/%Y'
Example output:
07/12/1988
22/04/2012
24/09/2012
27/08/2000
19/01/2008
21/10/1994
You can turn the problem into generating a random number between a number representing the first possible date and a number representing the last possible date (actually the one right after the last possible), in unix epoch format. Everything else is handled by standard date conversions. gawk
has a better random number resolution than bash
(float vs 15 bits integer), so I'll be using gawk
. Note that the rand()
result N is a float such that 0 <= N < 1, that's why the higher limit is increased below, it's a limit that can't be rolled. There's an optional 3rd parameter for the number of results.
#!/usr/bin/gawk -f
BEGIN {
first=mktime(ARGV[1] " 01 01 00 00 00")
last=mktime(ARGV[2]+1 " 01 01 00 00 00")
if (ARGC == 4) { num=ARGV[3] } else { num=1 }
ARGC=1
range=last-first
srand(sprintf("%d%06d", systime(), PROCINFO["pid"]))
for (i=1; i <= num; i++) {
print strftime("%d/%m/%Y", range*rand()+first)
}
}
For example:
./randomdate.gawk 1987 2017 6
26/04/1992
28/04/2010
21/04/2005
17/02/2010
06/10/2016
04/04/1998
Perl:
perl -MTime::Piece -sE '
my $t1 = Time::Piece->strptime("$y1-01-01 00:00:00", "%Y-%m-%d %H:%M:%S");
my $t2 = Time::Piece->strptime("$y2-12-31 23:59:59", "%Y-%m-%d %H:%M:%S");
do {
my $time = $t1 + int(rand() * ($t2 - $t1));
say $time->dmy;
} for 1..6;
' -- -y1=1987 -y2=2017
Sample output:
10-01-1989
30-04-1995
10-12-1998
02-01-2016
04-06-2006
11-04-1987