Reputation: 393
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?
Upvotes: 32
Views: 87076
Reputation: 694
I liked JDawg's answer but couldn't get it to work properly on a RHEL system I was working on. I was able to get this to work. Hopefully this will help someone. It displays the contents of a file with the converted timestamps in place.
cat filename | perl -pe 's/(\d+)/localtime($1)/e'
Upvotes: 2
Reputation: 236
To add to the answer, you can also replace localtime with gmtime in order to get the UTC time. I found this very useful in my Bash scripts:
UTC:
echo 1357810480 | perl -nE 'say scalar gmtime $_'
Local:
echo 1357810480 | perl -nE 'say scalar localtime $_'
You can replace say
with print
if you don't require a new line at the end of the output.
Upvotes: 0
Reputation: 9540
Or, if you have a file with embedded timestamps, you can convert them in place with:
cat [file] | perl -pe 's/([\d]{10})/localtime $1/eg;'
Upvotes: 7
Reputation: 386706
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.
Upvotes: 23
Reputation: 238296
You can use localtime
for that.
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($unix_timestamp);
Upvotes: 17
Reputation: 69314
A perfect use for Time::Piece (standard in Perl since 5.10).
use 5.010;
use Time::Piece;
my $unix_timestamp = 1e9; # for example;
my $date = localtime($unix_timestamp)->strftime('%F %T'); # adjust format to taste
say $date; # 2001-09-09 02:46:40
Upvotes: 21
Reputation: 4038
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
Upvotes: 38