在perl中的两个日期和时间模式之间打印日志文件

时间:2015-02-12 13:48:30

标签: perl parsing date logging

perl guru的

我有一个问题,我需要在两个日期范围之间打印日志文件,包括时间。

例如

log file btw (Current date & time and 1 week ago) or
log file btw (Current date & time and 1 month ago)

这就是我的日志文件的外观。

02/12/15 13:05 some text here
02/11/15 12:05 some text here
02/10/15 10:05 some text here
02/09/15 09:05 some text here
02/08/15 08:05 some text here
02/07/15 01:05 some text here
--
-
-o/p truncated
-
01/29/15 13:05 some text here
01/29/15 12:05 some text here
01/29/15 10:05 some text here
01/29/15 09:05 some text here
01/29/15 08:05 some text here
01/29/15 01:05 some text here

1 个答案:

答案 0 :(得分:1)

所以,要做到这一点你需要的是:

Time::Piece - 这是一个核心模块,可让您提取相应日期的数值。

特别是 - Time::Piecestrptime,它将格式化的时间转换为可比较的值。

E.g。

#!/usr/bin/perl
use strict;
use warnings;

use Time::Piece;

while (<DATA>) {
    my ( $date, $time ) = split;
    my $t = Time::Piece->strptime( "$date $time", "%m/%d/%y %H:%M" );
    print $t, "\n";
}   

__DATA__
01/29/15 13:05 some text here
01/29/15 12:05 some text here
01/29/15 10:05 some text here
01/29/15 09:05 some text here
01/29/15 08:05 some text here
01/29/15 01:05 some text here

然后,您可以在比较中使用$t来计算相对时间。 (这是一个特殊的价值,如果你用数字比较它,那就像'#epoch&time;时间一样。

E.g:

my $one_week_ago = time() - 7 * 24 * 60 * 60; 
if ( $t < $one_week_ago ) { #do something };