Perl で時間を扱う Time::Piece

古い残念なcgiスクリプトで、以下をよく見かけます。


($sec,$min,$hour,$mday,$month,$year,$wday,$stime) = localtime();
このあたりは、2000年あたりのコードなので、ざっくり忘れましょう。

Perlで時間を扱うモジュールですが、DateTimeとかTime::Pieceがあります。

DateTimeのほうが、いろいろできるようですが、Time::PieceはPerlのコアモジュール(インストールすると入ってる)だったりするので、普段は Time::Pieceで何とかしましょう。
多分、Time::Pieceのほうが軽い。

Usageはmetacpanにて Time::Piece - Object Oriented time objects - metacpan.org


use strict;
use warnings;
use Time::Piece;

my $now = localtime;

warn $now->datetime; # 2012-10-07T07:30:00
warn $now->datetime(T=>' '); # 2012-10-07 07:30:00
warn $now->epoch; # 1349562600
warn $now->tzoffset; # 32400

my $yearsterday = $now - 60 * 60 * 24;
warn $yearsterday->datetime(T => ' '); # 2012-10-06 07:30:00

○文字列からのパース


my $created_at = 'Sat Oct 06 21:38:38 +0000 2012';
my $t = Time::Piece->strptime($created_at,'%a %b %d %H:%M:%S %z %Y');

warn $t->datetime(T => ' '); # 2012-10-06 21:38:38

my $offset = ( 60 * 60 * 9 ) - $t->tzoffset();
$t += $offset;
warn $t->datetime(T => ' '); # 2012-10-07 06:38:38

ちなみに、タイムゾーンなところのBugが古いバージョンにはあるので、使うなら ver 1.20以降にしましょう。

参考:Time::Piece とタイムゾーンの甘い罠 - (ひ)メモ

私は思いっきりハマリマシタ。

corelistコマンドによると、Perl 5.14以降は、そのままでOKそうですね。


$ perl -MTime::Piece -E 'say $Time::Piece::VERSION'
1.20_01