Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Unix timestamp to a readable date in Perl

Tags:

timestamp

perl

I have some Unix timestamps (for example, 1357810480, so they're mainly in the past). How can I transform them into a readable date-format using Perl?

like image 587
hurley Avatar asked Sep 03 '25 05:09

hurley


2 Answers

Quick shell one-liner:

perl -le 'print scalar localtime 1357810480;'
Thu Jan 10 10:34:40 2013

Or, if you happen to have the timestamps in a file, one per line:

perl -lne 'print scalar localtime $_;' <timestamps
like image 153
Perleone Avatar answered Sep 04 '25 23:09

Perleone


You could use

my ($S, $M, $H, $d, $m, $Y) = localtime($time);
$m += 1;
$Y += 1900;
my $dt = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $Y, $m, $d, $H, $M, $S);

But it's a bit simpler with strftime:

use POSIX qw( strftime );
my $dt = strftime("%Y-%m-%d %H:%M:%S", localtime($time));

localtime($time) can be substituted with gmtime($time) if it's more appropriate.

like image 20
ikegami Avatar answered Sep 04 '25 23:09

ikegami