为什么我的Time :: Piece代码给出了奇怪的结果?

时间:2014-04-15 06:25:09

标签: perl datetime time

我正在尝试对Perl中的两个日期进行基本比较。当前日期时间和过去时间是正确的,但减法给出不正确的结果。差异应该是~24小时,但它返回~13小时。知道为什么以及如何解决它?感谢。

use Time::Piece;

my $now = Time::Piece->new;
my $then = Time::Piece->strptime("2014-04-14 16:30:20", "%Y-%m-%d %H:%M:%S");
my $diff = $now - $then;

print "Current time: $now\n";
print "Past time: $then\n";
print "Diff in Seconds:", $diff, "\n";
print "Pretty Diff:", $diff->pretty, "\n";

Results
------
Current time: Tue Apr 15 16:13:39 2014
Past time: Mon Apr 14 16:30:20 2014
Diff in Seconds:49399
Pretty Diff:13 hours, 43 minutes, 19 seconds

2 个答案:

答案 0 :(得分:9)

两个时间点位于不同的时区。所以差异实际上是正确的。你可以用

看到
print $now->tzoffset, "\n";    # 7200 (I am in UTC +2 hence have 7200s offset)
print $then->tzoffset, "\n";   # 0

所以基本上$then是UTC时间,而$now是你的环境认为的时区。 要解决这个问题,你需要决定你想要的时区。

答案 1 :(得分:2)

正如DeVadder已经说过的那样,因为Time::Piece在解析时间内默认为UTC

假设您希望使用localtime完成所有操作,您实际上可以鼓励解析时间从本地继承其时区,如下所示:

use Time::Piece;

use strict;
use warnings;

my $now = Time::Piece->new;
my $then = localtime->strptime("2014-04-14 16:30:20", "%Y-%m-%d %H:%M:%S");
my $diff = $now - $then;

print "Current time: $now\n";
print "Past time: $then\n";
print "Diff in Seconds:", $diff, "\n";
print "Pretty Diff:", $diff->pretty, "\n";

输出:

Current time: Tue Apr 15 17:12:08 2014
Past time: Mon Apr 14 16:30:20 2014
Diff in Seconds:88908
Pretty Diff:1 days, 0 hours, 41 minutes, 48 seconds