2013-02-25 159 views

回答

12

您可以使用localtime

my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($unix_timestamp); 
+0

謝謝,但我想存儲 – hurley 2013-02-25 10:08:24

+0

是啊,這將使在'$ time'數組。之後,小時在'$ time [2]'例如。 – Andomar 2013-02-25 10:09:31

+0

謝謝,但我想直接在一個變量中存儲格式化的日期。你有看到這種可能嗎?我的當前解決方案似乎可以保存當前日期,不管給定時間戳的年齡有多大 – hurley 2013-02-25 10:11:05

12

你可以使用

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

但它與strftime簡單一些:

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

localtime($time)可以gmtime($time)如果是比較合適的替代。

15

Time::Piece(從5.10起的Perl中的標準)的完美用法。

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 
+0

''%f%T''不適用於我(也許是因爲我的區域設置),但'%Y%m-%d''確實有效。 – 2017-08-27 02:44:28

22

快速殼的一行:

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

或者,如果你碰巧有時間戳的文件,每行一個:

perl -lne 'print scalar localtime $_;' <timestamps 
+0

優雅而簡單 – 2013-10-22 17:00:48

+2

這應該是被接受的答案。其他人可以在人們希望在他們的日期更深入時使用。只是看一個時間戳,'標量本地時間',完成。 – felwithe 2016-03-30 21:09:41

4

或者,如果你有一個帶有嵌入時間戳的文件,您可以將其轉換爲:

$ cat [file] | perl -pe 's/([\d]{10})/localtime $1/eg;' 
+1

這正是我需要的!我可以將我的日誌文件輸入到perl單線程和BINGO即時日期/時間。 – rob 2015-09-11 14:41:10

0

我喜歡JDawg的回答,但無法在我正在研究的RHEL系統上正常工作。我能夠得到這個工作。希望這會幫助某人。它顯示轉換後的時間戳文件的內容。

cat filename | perl -pe 's/(\d+)/localtime($1)/e'

相關問題