Perl比较两个日期列表的最佳方式&数字

时间:2014-04-04 01:27:28

标签: sql arrays perl hash

我不确定从哪里开始,所以我将从头开始。我有两个列表,每个列表包含两列。日期/时间列和数字列,格式如下:

2012-11-27 13:16:19.473           6
2012-11-27 13:17:17.910         710
2012-11-28 15:21:52.513         696
2012-11-29 08:40:16.430         541
2012-11-20 09:07:45.813         347
2012-12-01 01:00:09.230         647
2012-12-01 14:53:22.200         488
2012-12-04 18:42:02.727         797

日期/时间始终是唯一的,但第二列在两个列表中都有重复。我首先需要将第一个列表的第二列与第二个列表的第二列进行比较。每次在第二列中找到匹配项时,我需要比较相应的日期。如果日期在彼此的(+或 - )5天之内,我需要减去它们并找出小时数的差异,然后计算每种差异的出现次数。

例如:

清单1:

2014-03-27 17:00:00.000         582
2012-12-04 18:42:02.727         797

清单2:

2014-03-28 17:00:00.000         582
2012-12-04 18:42:02.727         793

所需的输出将是1次出现24小时。

我不确定存储来自数据库的列表的最佳方法。以日期为键的哈希值,因为第二列有重复项或数组或数组数组或者......帮助我!

谢谢!

2 个答案:

答案 0 :(得分:0)

要回答您的第一个问题,与日期进行比较的最简单方法是什么?

我建议使用Time::Piece

use strict;
use warnings;

use Time::Piece;

my $str1 = '2014-03-27 17:00:00';
my $str2 = '2014-03-28 17:00:00';

my $t1 = Time::Piece->strptime($str1, '%Y-%m-%d %H:%M:%S');
my $t2 = Time::Piece->strptime($str2, '%Y-%m-%d %H:%M:%S');

print "$t1\n";
print "$t2\n";

my $diff = $t2 - $t1;

print "$diff\n";

答案 1 :(得分:0)

Time::Piece是一个有用的模块,但不能进行亚秒计算。您可能需要使用DateTime模块。

这是一种方法:

#!/usr/bin/perl

use strict;
use warnings;
use DateTime::Format::Strptime;

# Set the pattern for your timestamp 

my $dp = DateTime::Format::Strptime->new(pattern => '%Y-%m-%d %H:%M:%S.%3N');

open my $fh1, '<', "List1";
open my $fh2, '<', "List2";

my %ids;  
my ($ts, $id);

# Read List1 and create a hash with id as keys and timestamp as values

while (<$fh1>) {
    ($ts, $id) = /(\S+\s\S+)\s+(\S+)/;  
    $ids{$id} = $ts; 
}

# Read the second file and check if id exists in hash

while (<$fh2>) {
    ($ts, $id) = /(\S+\s\S+)\s+(\S+)/;
    if (exists $ids{$id}) {

# If the id is present we find the difference of timestamp and print it

        my $diff = $dp->parse_datetime($ts)-$dp->parse_datetime($ids{$id});
        print "Difference found for id " . $id . "\n";
        print 
        $diff->days . " Day(s) " . 
        $diff->hours . " Hour(s) " . 
        $diff->minutes . " Minute(s) " . 
        $diff->seconds . " Second(s) " . "\n";
    }
}

输出:

Difference found for id 582
1 Day(s) 0 Hour(s) 0 Minute(s) 0 Second(s) 
相关问题