VolleyballAddictSandiego VolleyballAddictSandiego - 9 months ago 39
Perl Question

How to convert unix epoch time to readable format in perl

How do I convert 1461241125.31307 in perl. I tried:

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";

2016-4-21 5:18:45
(no padding of hour)

How do I pad it and make it GMT. I want the result to say
2016-04-21 12:18:45

Thanks for the answers folks.

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


Easiest way:

print scalar localtime $unix_timestamp;

Documentation: http://perldoc.perl.org/functions/localtime.html

For GMT, use gmtime:

print scalar gmtime $unix_timestamp;

Documentation: http://perldoc.perl.org/functions/gmtime.html (Basically says: Everything like localtime, but outputs GMT time.)

For custom formats, try DateTime:

use DateTime;

my $dt = DateTime->from_epoch(epoch => $unix_timestamp);
print $dt->strftime('%Y-%s');

See http://search.cpan.org/perldoc?DateTime for all options. Lots of formats could be created even more easily using the predefined DateTime Formatters: http://search.cpan.org/search?query=DateTime%3A%3AFormat&mode=all