PERL如何将本地时间格式转换为unixtime

时间:2012-08-31 11:18:07

标签: perl unix-timestamp

有人可以帮忙吗?我在日志文件文件中有一个时间值,格式如下:

2012年8月28日星期二09:50:06

我需要将此时间值转换为unixtime。

问候

3 个答案:

答案 0 :(得分:5)

这里你最好的选择是Time::Piece,这是一个核心模块,因此不需要安装。它有一个用于解析时间/日期字符串的strptime方法和一个用于返回Unix纪元时间的epoch方法

将其滚动到子程序中很方便,如下所示

use strict;
use warnings;

use Time::Piece ();

print date_to_epoch('Tue Aug 28 09:50:06 2012'), "\n";

sub date_to_epoch {
   return Time::Piece->strptime($_[0], '%a %b %d %T %Y')->epoch;
}

<强>输出

1346147406

答案 1 :(得分:2)

这对我有用(需要DateTime::Format::Strptime):

#!/usr/bin/perl

use strict;
use warnings;

use DateTime::Format::Strptime;

my $strp = DateTime::Format::Strptime->new(
  pattern   => '%a %b %d %H:%M:%S %Y',
  locale    => 'en_US',
  time_zone => 'local',  # Or even something like 'America/New_York'
  on_error  => 'croak',
);

my $dt = $strp->parse_datetime('Tue Aug 28 09:50:06 2012');

print $dt->epoch() . "\n";

答案 2 :(得分:1)

使用Time :: Piece模块中的strptime函数来解析日期,然后使用strftime函数返回Unix时间戳。

use Time::Piece;
$parsed = Time::Piece->strptime("Tue Aug 28 09:50:06 2012", "%a %b %e %T %Y");
$unixtime = $parsed->strftime("%s");
相关问题