Skip to content

Instantly share code, notes, and snippets.

@issm
Created March 5, 2014 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save issm/9366888 to your computer and use it in GitHub Desktop.
Save issm/9366888 to your computer and use it in GitHub Desktop.
=head1 NAME
randtime.pl - prints datetime randomly
=head1 SYNOPSIS
randtime.pl <options>
# randtime.pl -n 20
# randtime.pl --date=2014-03-01 -n 20
# randtime.pl --range=2014-01-01T00:00:00..2014-01-10T00:00:00 -n 50
=head1 OPTIONS
=over 4
=item --date=$date
=item --range=${datetime1}..${datetime2}
=item --n=$n
=item --help
=back
=cut
use 5.18.0;
use warnings;
use utf8;
use Getopt::Long qw/:config posix_default no_ignore_case bundling/;
use Time::Piece ();
use Pod::Usage;
my %opts = (
date => Time::Piece->localtime->date,
range => undef,
n => 10,
help => 0,
);
GetOptions(
'date=s' => \$opts{date},
'range=s' => \$opts{range},
'n=i' => \$opts{n},
'h|help' => \$opts{help},
) or pod2usage( 1 );
for ( keys %opts ) { delete $opts{$_} unless defined $opts{$_} }
pod2usage( 0 ) if $opts{help};
sub t {
my ($t) = @_;
return ( $t =~ /^\d{10}$/ )
? Time::Piece::localtime( $t )
: Time::Piece::localtime->strptime( $t, '%Y-%m-%dT%H:%M:%S' );
}
sub list {
my ( $t1, $t2, $n) = @_;
my @t;
for my $i ( 1 .. $n ) {
my $r = rand();
my $t = int( $t1 + ($t2 - $t1) * $r );
push @t, t( $t )->datetime;
}
return wantarray ? @t : \@t;
}
sub main {
my %args = @_;
my @r = exists $args{range}
? ( split /\.\./, $args{range} )
: ( map "$args{date}T$_", '00:00:00', '23:59:59' );
my ($t1, $t2) = map t( $_ )->epoch, @r;
say $_ for list( $t1, $t2, $args{n} );
return 0;
}
main( %opts );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment