如何在perl中更改日期/时间字符串的格式?(具体问题)

1 string formatting perl datetime

我有一个从日志文件解析的示例字符串,格式如下:

"Mon Apr 25 17:47:19 2011"

我希望它看起来像

"Mon Apr 25 05:47 PM 2011"

我一般如何做到这一点?(即每次当然不会是相同的字符串).

非常感谢.

hob*_*bbs 10

如果有疑问,使用DateTime通常是一个不错的选择.在这种情况下,您可以:

use DateTime;
use DateTime::Format::Strptime;

my $parser = DateTime::Format::Strptime->new(
    pattern => '%a %b %d %H:%M:%S %Y'
);

my $dt = $parser->parse_datetime('Mon Apr 25 17:47:19 2011');
print $dt->strftime('%a %b %d %I:%M%p %Y'), "\n";
Run Code Online (Sandbox Code Playgroud)

如果需要有关模式的信息,请参阅strftime文档DateTime手册中的类似部分.

你也可以将它使用strftime在功能POSIXstrptime函数POSIX :: strptime,但接口不太愉快.