2017-08-03 127 views
-1

这些是我的数据;Perl:计算日期差异和平均日期

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的...

+3

你是什么意思 “_average days_” 是什么意思? – zdim

+0

1.从变量/行中提取日期(使用'split'或regex或两者)2.找到您喜欢的日期/时间模块。一个简单的选择是[DateTime](http://search.cpan.org/~drolsky/DateTime-1.43/lib/DateTime.pm),但肯定还有其他的。他们中的大多数都有你需要的设施。 3.将日期/时间设置为模块所需的格式 – zdim

+0

您的日期时间格式非常标准,许多模块都能理解它,所以您无需解析它(一旦您从数据线中获取它你展示的) – zdim

回答

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不支持亚秒级的精度,所以结果可能是几微秒关闭。