如何在 perl 中将 unix 纪元时间转换为可读格式

Vol*_*ego 4 perl

如何在 perl 中转换 1461241125.31307。我试过:

use Date::Parse;
$unix_timestamp = '1461241125.31307';
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($unix_timestamp);
$mon += 1;
$year += 1900;
$unix_timestamp_normal = "$year-$mon-$mday $hour:$min:$sec";
Run Code Online (Sandbox Code Playgroud)

结果:(2016-4-21 5:18:45没有填充小时)

我如何填充它并使其成为格林威治标准时间。我要结果说2016-04-21 12:18:45


谢谢大家的回答。

use DateTime;
$unix_timestamp = '1461241125.31307';
my $dt = DateTime->from_epoch(epoch => $unix_timestamp);
print $dt->strftime('%Y-%m-%d %H:%M:%S'),"\n";
Run Code Online (Sandbox Code Playgroud)

Seb*_*ian 7

最简单的方法:

print scalar localtime $unix_timestamp;
Run Code Online (Sandbox Code Playgroud)

文档:http : //perldoc.perl.org/functions/localtime.html

对于 GMT,请使用gmtime

print scalar gmtime $unix_timestamp;
Run Code Online (Sandbox Code Playgroud)

文档:http : //perldoc.perl.org/functions/gmtime.html(基本上说:一切都像localtime,但输出 GMT 时间。)

对于自定义格式,请尝试DateTime

use DateTime;

my $dt = DateTime->from_epoch(epoch => $unix_timestamp);
print $dt->strftime('%Y-%s');
Run Code Online (Sandbox Code Playgroud)

有关所有选项,请参阅http://search.cpan.org/perldoc?DateTime。使用预定义的 DateTime Formatters 可以更轻松地创建许多格式:http ://search.cpan.org/search?query = DateTime%3A%3AFormat&mode= all


ike*_*ami 5

use POSIX qw( strftime );

my $epoch_ts = '1461241125.31307';

say strftime('%Y-%m-%d %H:%M:%S', gmtime($epoch_ts));
Run Code Online (Sandbox Code Playgroud)