【问题标题】:Convert time in GMT to current time zone in perl将 GMT 时间转换为 perl 中的当前时区
【发布时间】:2014-11-05 01:44:09
【问题描述】:

我想将 GMT 时间字符串转换为我的系统时区。 前任。 格林威治标准时间 2014 年 11 月 4 日星期二 22:03:03

我的机器时区是 PST,所以输出应该是:2014-11-04 14:03:03 PST

我可以在 bash 中做到这一点,但找不到 perl 的任何解决方案。

Bash 解决方案=> timestamp_local=date "+%Y-%m-%d %H:%M:%S %Z" -d "$timestamp_GMT"

谁有 perl 的解决方案?

PS:我必须处理一个巨大的文件(大约 100-200MB 的文本文件)。所以,我想要一个优化的解决方案。

【问题讨论】:

  • 您可以使用系统命令从 perl 脚本中调用您的 bash 解决方案。
  • 你有Time::Local吗?
  • @GriffinG 我有一个巨大的文件,调用此转换的系统会对我的脚本的运行时间产生不利影响。我应该在问题中提到这一点。
  • @Elliott Frisch 是的,我有。

标签: perl


【解决方案1】:

与 DateTime 和朋友一起使用很简单。

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

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

my $format = '%a %b %d %H:%M:%S %Y %Z';
my $time_string = 'Tue Nov 04 22:03:03 2014 GMT';

my $dt_p = DateTime::Format::Strptime->new(
  pattern => $format,
  time_zone => 'UTC',
);

my $time = $dt_p->parse_datetime($time_string);

say $time->strftime('%a %b %d %H:%M:%S %Y %Z');

$time->set_time_zone('America/Los_Angeles');

say $time->strftime('%a %b %d %H:%M:%S %Y %Z');

更新:this old answer 展示了如何使用核心模块 Time::Piece 做一些非常相似的事情。

【讨论】:

    【解决方案2】:

    POSIX 库应该足以做到这一点;

    use strict;
    use feature qw/say/;
    use POSIX qw(strftime tzset);
    
    say strftime("%Y %d %m %H:%M:%S GMT", gmtime(time));    # GMT
    say strftime("%Y %d %m %H:%M:%S %Z", localtime(time));  # Local Time
    
    # Set to  custom timezone
    $ENV{TZ} = 'America/Los_Angeles';
    tzset;
    say strftime("%Y %d %m %H:%M:%S %Z", localtime(time));  # Custom Zone
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多