Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert unix epoch time to readable format in perl

Tags:

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

result: 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";
like image 608
VolleyballAddictSandiego Avatar asked May 13 '16 08:05

VolleyballAddictSandiego


2 Answers

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

like image 91
Sebastian Avatar answered Oct 06 '22 20:10

Sebastian


use POSIX qw( strftime );

my $epoch_ts = '1461241125.31307';

say strftime('%Y-%m-%d %H:%M:%S', gmtime($epoch_ts));
like image 40
ikegami Avatar answered Oct 06 '22 22:10

ikegami