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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can use localtime
for that.
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($unix_timestamp);
回答2:
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
回答3:
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
回答4:
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.
回答5:
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;'
回答6:
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'