使用strptime解析相对于本地时间的时间戳

时间:2015-04-12 10:27:19

标签: perl

我正在尝试相对于当前当地时间进行一些日期计算。 例如:

use feature qw(say);
use strict;
use warnings;

use Time::Piece;

my $fmt = '%Y-%m-%d_%H:%M:%S';
my $timestamp = "2015-04-12_11:07:27";

# This gives incorrect $t1 relative to localtime
my $t1 = Time::Piece->strptime( $timestamp, $fmt );
my $t2 = localtime;

say "Local time: " . localtime;
say "Local time epoch: " . time;

say $t1->epoch();
say $t2->epoch();

my $timestamp1 = $t1->strftime( $fmt );
my $timestamp2 = $t2->strftime( $fmt );

say $timestamp1;
say $timestamp2;

my $delta = $t2 - $t1;

say $delta;

示例输出:

Local time: Sun Apr 12 12:21:49 2015
Local time epoch: 1428834109
1428836847
1428834109
2015-04-12_11:07:27
2015-04-12_12:21:49
-2738

这显然给出了-2738的错误时差。 (它应该是一个正数)

2 个答案:

答案 0 :(得分:3)

如果您解析的日期时间没有时区信息,则假定为UTC。您可以通过在脚本中添加以下两行来看到这一点:

say "tzo1 = ",$t1->tzoffset;
say "tzo2 = ",$t2->tzoffset;

在巴黎,以上内容输出如下:

tzo1 = 0
tzo2 = 7200

您可以使用localtime而不是Time::Piece作为调用者的未记录功能,将默认值覆盖为本地时区。

$ perl -MTime::Piece -E'
   say Time::Piece->strptime("2015-04-12_11:07:27", "%Y-%m-%d_%H:%M:%S")->tzoffset;
   say localtime  ->strptime("2015-04-12_11:07:27", "%Y-%m-%d_%H:%M:%S")->tzoffset;
'
0
7200

做那个微小的改变会得到你期待的答案。

$ perl -MTime::Piece -E'
   say localtime->strptime("2015-04-12_11:07:27", "%Y-%m-%d_%H:%M:%S") - localtime;
'
5524

答案 1 :(得分:2)

我认为可以使用Date::Time完成此操作:

use feature qw(say);
use strict;
use warnings;

use DateTime;
use DateTime::Format::Strptime;
use DateTime::Duration;

my $strp = DateTime::Format::Strptime->new(
    pattern   => '%Y-%m-%d_%H:%M:%S',
    time_zone => 'local',
);

my $timestamp = "2015-04-12_11:07:27";
my $dt1 = $strp->parse_datetime( $timestamp );
my $dt2 = DateTime->now();
say $dt2->subtract_datetime_absolute( $dt1 )->seconds();