Perl:计算日期差异和平均日期

时间:2017-08-03 08:53:39

标签: perl date

这些是我的数据;

 Ticket Submitted_date      Ticket closed_date
 2017-05-11 12:47:08.2      2017-05-26 07:00:16.0
 2017-05-11 13:23:10.96     2017-05-27 22:01:02.0
 2017-05-11 13:23:02.483    2017-05-24 08:10:20.0
 2017-05-11 13:28:35.247    2017-05-24 08:12:33.0 

代码如下,

use strict;
use warnings;

my $qstr = "select id as 'id', status as 'status', $subject.title as 'title', $subject.component as 'component', $subject.submitted_date as 'submitted_date', $subject.closed_date as 'closed_date' where ($subject.status = 'complete' OR $subject.status = 'rejected')";
my $results = &search($api, $tenant, $subject, $qstr); 

foreach my $singleRow (@$results) {
        my $title =$singleRow->{'title'};
        my $component = $singleRow->{'component'};
        my $sub_date = $singleRow->{'submitted_date'};
        my $closed_date = $singleRow->{'closed_date'};

       $sub_date =~ /^(.{4})-(.{2})-(.{2})T(.{2}):(.{2}):(.{2})\.(.{3})/;

不知道如何计算上述数据的平均天数。 需要帮助...... Perl新手......

1 个答案:

答案 0 :(得分:3)

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };    
use Syntax::Construct qw{ /r }; # /r in 5.014

use Time::Piece;
use Time::Seconds;

my $results = [[ '2017-05-11 12:47:08.2',   '2017-05-26 07:00:16.0' ],
               [ '2017-05-11 13:23:10.96',  '2017-05-27 22:01:02.0' ],
               [ '2017-05-11 13:23:02.483', '2017-05-24 08:10:20.0' ],
               [ '2017-05-11 13:28:35.247', '2017-05-24 08:12:33.0' ]];

my $sum = 0;
for my $single_row (@$results) {
    my ($from, $to) = map 'Time::Piece'->strptime(
                           s/\.[0-9]+$//r, '%Y-%m-%d %H:%M:%S'
                      ),
                      @$single_row;
    my $delta = $to - $from;
    $sum += $delta;
}
my $average = $sum / @$results;
say 'AVERAGE: ', $average / ONE_DAY, ' days.';

Time::Piece不支持亚秒级精度,因此结果可能会减少几微秒。