将历史时间戳从UTC转换为本地

时间:2016-04-25 16:03:58

标签: perl utc

我有一个过去时间戳的文件,全部是UTC格式。我需要将这些转换为东部时间。我已经接近了,但它在夏令时转换中变得混乱。

#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;

#DST not in effect
my $utc = '2015-03-08 01:59:00.000';
my $local = utc_to_local($utc);
print "DST not in effect: utc($utc) = local($local)\n";

#DST not in effect
$utc = '2015-03-08 02:00:00.000';
$local = utc_to_local($utc);
print "DST not in effect: utc($utc) = local($local)\n";


sub utc_to_local
{
    my $utc_ts = $_[0]; #this has ms on right side, we want left 19 characters
    $utc_ts = substr $utc_ts, 0, 19;
    my $local_tp = localtime->strptime( $utc_ts, '%Y-%m-%d %H:%M:%S' );
    $local_tp = $local_tp + $local_tp->tzoffset();

    return $local_tp->strftime('%Y-%m-%d %H:%M:%S');
}

正如您所看到的,如果我在3/8和UTC时间凌晨2点在UTC时间凌晨1点59分尝试,它认为已经发生了变化,但是上午2点UTC仅在晚上9点的3/7。远离夏令时转换,它可以正确地进行-5和-4偏移。

DST not in effect: utc(2015-03-08 01:59:00.000) = local(2015-03-07 20:59:00)
DST not in effect: utc(2015-03-08 02:00:00.000) = local(2015-03-07 22:00:00)

1 个答案:

答案 0 :(得分:3)

$utc_ts不是当地时间。

my $local_tp = localtime->strptime( $utc_ts, '%Y-%m-%d %H:%M:%S' );

应该是

my $utc_tp = Time::Piece->strptime( $utc_ts, '%Y-%m-%d %H:%M:%S' );

然后就是转换到本地时间的问题。

$local_tp = $local_tp + $local_tp->tzoffset();

应该是

my $local_tp = localtime($utc_tp->epoch);

所有在一起:

#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw( );
use Time::Piece;

sub utc_to_local {
    my ($utc_ts) = @_;
    my $utc_tp = Time::Piece->strptime( $utc_ts, '%Y-%m-%d %H:%M:%S' );
    my $local_tp = localtime($utc_tp->epoch);
    return $local_tp->strftime('%Y-%m-%d %H:%M:%S');
}

sub local_to_utc {
    my ($local_ts) = @_;
    my $local_tp = Time::Piece->strptime( $local_ts, '%Y-%m-%d %H:%M:%S' );
    my $utc_tp = gmtime($local_tp->epoch);
    return $utc_tp->strftime('%Y-%m-%d %H:%M:%S');
}

{
    $ENV{TZ} = 'America/Toronto';
    POSIX::tzset();

    # DST not in effect
    my $utc = '2015-03-08 06:59:00.000';
    my $local = utc_to_local(substr($utc, 0, -4));
    print "DST not in effect: utc($utc) = local($local)\n";

    # DST not in effect
    $utc = '2015-03-08 07:00:00.000';
    $local = utc_to_local(substr($utc, 0, -4));
    print "DST not in effect: utc($utc) = local($local)\n";
}

输出:

DST not in effect: utc(2015-03-08 06:59:00.000) = local(2015-03-08 01:59:00)
DST not in effect: utc(2015-03-08 07:00:00.000) = local(2015-03-08 03:00:00)