要减去两个Time:Piece对象

时间:2016-04-16 08:31:46

标签: perl

我想在几分钟内获得时间差异。两个要比较的时间都在同一时区,所以不用担心时区差异等等。

假设Start_time = 14 Apr 2016 05:02:26(从日志行收集)和结束时间是机器的当前时间,

我想计算end time - start time。为此,我需要以当前时间的格式开始时间。 我尝试减去当前时间,它已经是一个Time :: Piece对象并将$start_time转换为Time:Piece对象。

但是我得到了“在C:/Perl/lib/Time/Piece.pm第469行,第1071883行解析时间错误。”错误。请建议。 此错误的“1071883”数字每次运行脚本时都会发生变化。不确定它是否是一种垃圾价值或者是什么。

使用以下建议的答案编辑代码 我低于输出。似乎问题即将到来,因为$ now现在包含像星期六那样的DAY值,但我们的$ start_time并不存在。但是,当我们从日志文件中收集日期值时,我无法对开始时间进行任何更改,例如添加日期值。如果问题是由于我说的原因,请建议如何忽略$ now的那天价值。

输出:

last line of log: 16 Apr 2016 03:41:49 -- DEBUG -- 16 Apr 2016 03:41:49 
Time is Sat Apr 16 03:43:02 2016 
difference is 21673

以下是我的尝试:

#get last line of log
open my $fh ,"<","$slogfile";
my $last_line;
$last_line = $_,while (<$fh>);      
print OUTLOG "last line of log: $last_line \n";

if ($last_line=~ m/^(\d\d) (\w{3}) (\d{4}) (\d\d):(\d\d):(\d\d) --/) {
    $start_time = "$1 $2 $3 $4:$5:$6";
    print OUTLOG "$start_time\n";
} else {
    print OUTLOG "pattern matching didnt work\n";
}

#get current time
my $t = localtime;
#my $current_time = $t ;
print OUTLOG "Time is $current_time \n";

my $format = '%d %b %Y %H:%M:%S';

my $diff = $t - Time::Piece->strptime($var, $format);

print OUTLOG "difference is  $diff \n";

1 个答案:

答案 0 :(得分:1)

您的格式与日期格式不符。你正在使用的格式是&#34;&#39;%a%b%d%H:%M:%S%Y&#34;,这将匹配&#34; Thu Apr 14 05:02 :2016年6月26日你可以从&#34; man strftime&#34;中获得你的格式的各种部分的解释。或者&#34; man strptime&#34;。

我已在此示例中更正了格式定义。

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Piece;

my $format = '%d %b %Y %H:%M:%S';

my $start_time = '14 Apr 2016 05:02:26';
my $now = localtime;

my $diff = $now - Time::Piece->strptime($start_time, $format);

say "$diff seconds"; # $diff stringifies to seconds
say $diff->minutes, ' minutes';

输出结果为:

186402 seconds
3106.7 minutes

<强>更新

  

似乎问题来了,因为$ now现在包含DAY值   星期六但我们的$ start_time并不存在。但是我无法改变   开始时间就像我们收集日期值一样   来自日志文件。如果问题是由于我说的原因,那么   建议如何忽略$ now的那天价值。

没有。这根本不是问题。如果您打印出从$start_time解析的Time :: Piece对象,那么您将看到还包含了日期名称。这就是Time :: Piece对象如何进行字符串化。

实际问题更加微妙。似乎当Time :: Piece解析日期字符串时,它假定它是UTC,除非该字符串包含显式时区。根据你所说的,我假设你在美国东海岸,这可以解释你所得到的~6小时差异。

我正在进一步调查这一点,并且几乎肯定会向Time :: Piece提交补丁以修复此问题(它可能只是一个文档补丁,可以使行为更加清晰)。但与此同时,你需要一个修复。这非常简单。您只需要为代码添加时区。您的代码的相关部分现在将如下所示:

my $format = '%d %b %Y %H:%M:%S%z'; # %z added here

# Append timezone here (-0600 as you're six hours behind UTC -
# adjust that if my assumption is wrong)
my $diff = $t - Time::Piece->strptime($var . '-0600', $format);

或者(正确地,在Borodin的评论中指出)你可以切换到全程使用UTC。

my $t = gmtime;

my $format = '%d %b %Y %H:%M:%S';

my $diff = $t - Time::Piece->strptime($var, $format);
相关问题