如何将文本日期转换为时间戳?

时间:2011-10-11 13:07:41

标签: perl

如何以文本格式转换日期:

23.10.2011  11:35:00

到时间戳?

3 个答案:

答案 0 :(得分:18)

使用Time::Local,您可以执行以下操作:

use Time::Local;

my $date = '23.10.2011  11:35:00';
my ($mday,$mon,$year,$hour,$min,$sec) = split(/[\s.:]+/, $date);
my $time = timelocal($sec,$min,$hour,$mday,$mon-1,$year);
print $time,"\n",scalar localtime $time;

<强>输出:

1319362500
Sun Oct 23 11:35:00 2011

答案 1 :(得分:16)

我会调查DateTimeparsing modules

perl -MDateTime::Format::Strptime -le'$strp = DateTime::Format::Strptime->new( pattern => "%d.%m.%Y  %T", time_zone => "local"); $dt = $strp->parse_datetime("23.10.2011  11:35:00"); print $dt->epoch'
1319384100 at -e line 1.

与上述相同,但不是单行:

use DateTime::Format::Strptime;
my $strp = DateTime::Format::Strptime->new(
   pattern => '%d.%m.%Y  %T',
   time_zone => 'local',
);
my $dt = $strp->parse_datetime('23.10.2011  11:35:00');
print $dt->epoch;

答案 2 :(得分:1)

您可以使用Time::Piece(一个核心模块)。可以在strptime的手册页上找到格式。

use Time::Piece;
my $tp = Time::Piece->strptime("23.10.2011  11:35:00", 
                               "%d.%m.%Y  %H:%M:%S");
print $tp->epoch; # 1319369700
print $tp;        # "Sun Oct 23 11:35:00 2011"