Home > database >  How to generate a DateTime range by step of 5 minutes?
How to generate a DateTime range by step of 5 minutes?

Time:02-14

How to generate a DateTime range by step of 5 minutes? The following is the output:

2022-02-13 00:00:00, 2022-02-13 00:05:00
2022-02-13 00:05:00, 2022-02-13 00:10:00
2022-02-13 00:10:00, 2022-02-13 00:15:00
2022-02-13 00:15:00, 2022-02-13 00:20:00
...
2022-02-13 23:45:00, 2022-02-13 23:50:00
2022-02-13 23:50:00, 2022-02-13 23:55:00
2022-02-13 23:55:00, 2022-02-14 00:00:00

CodePudding user response:

Sequence operator can be used

# when to start when to finish
my $start = DateTime.now.truncated-to("day");
my $end   = $start.later(:1day);

# after start, add 5 mins repeatedly, and stop when end is exceeded
say $start, *.later(:5minutes) ... * >= $end;

CodePudding user response:

Use the Interval module.

use Interval;
my $dt = Interval[300].new(time);
say $dt   for ^5; 

2022-02-13T15:29:03Z
2022-02-13T15:34:03Z
2022-02-13T15:39:03Z
2022-02-13T15:44:03Z
2022-02-13T15:49:03Z

CodePudding user response:

my $dt = Date.today.DateTime;

$dt.clone: formatter => { .yyyy-mm-dd ~ q{ } ~ .hh-mm-ss }\
andthen $_, *.later(:5minute) ... * eqv $dt.later(:1day)  
andthen .rotor: 2 => -1 
andthen .map: *.join(q{, }).put

CodePudding user response:

I come up with another solution:

sub MAIN() {
    my $fmt = {sprintf "d-d-d d:d:d", .year, .month, .day, .hour, .minute, .second};

    my @dates = gather given Date.today {
        my $current-datetime = .DateTime;
        while $current-datetime <= .succ.DateTime {
            take $current-datetime;
            $current-datetime = $current-datetime   Duration.new(300.0);
        }
    }

    for @dates.rotor(2 => -1) -> $pair {
        printf("%s, %s\n", DateTime.new($pair[0].Str, formatter => $fmt), DateTime.new($pair[1].Str, formatter => $fmt));
    }
}
  • Related