【问题标题】:Perl strptime format differs from strftimePerl strptime 格式与 strftime 不同
【发布时间】:2013-11-29 00:26:12
【问题描述】:

我正在尝试使用格式如下的日期字符串:

YYYY-MM-DDThh:mm:ss

生成该字符串的strftime格式为%FT%T:

perl -MPOSIX=strftime -E 'say strftime q{%FT%T}, localtime;'

但是当我尝试用Time::Piece解析这个日期字符串时:

perl -MPOSIX=strftime -MTime::Piece -E '
  say strftime q{%FT%T}, localtime;
  Time::Piece->strptime( strftime(q{%FT%T}, localtime), q{%FT%T});
'

我收到了这个错误:

2013-11-15T17:32:58 在 /usr/local/lib/perl/5.14.2/Time/Piece.pm 第 469 行解析时间时出错。

或者如果我试试这个:

perl -MPOSIX=strftime -MTime::Piece -E 'Time::Piece->strptime(strftime(q{%F}, localtime), q{%F});'

我知道了:

strptime 中字符串末尾的垃圾:2013-11-15 在 /usr/local/lib/perl/5.14.2/Time/Piece.pm 第 469 行。

在 man 中,%F 是 strptime 和 strftime 中的 ISO8601 日期格式。 strptime 是否向后兼容 strftime?

【问题讨论】:

  • 以上所有内容都适用于我在 Scientific Linux 6.4 上的 Perl 5.10.1。
  • @ThisSuitIsBlackNot,你是幸运的:)

标签: perl strftime strptime


【解决方案1】:

该模块使用自己的strptime 实现,它不理解%F。它没有实现自己的strftime。这是一场等待发生的灾难——您绝对应该使用来自同一来源的strftimestrptimeTime::Piece::strptime 看起来像是从一个没有广泛可用的标准化 strptime 的时代的绝望之举。

现在strptime 在 POSIX 中,我希望 POSIX.pm 将其导出,以便您可以使用系统的 strptime。但显然该模块也未能跟上。有一个单独的 POSIX::strptime module 可以为您提供 C 库的 strptime 而不会受到干扰。我建议使用它。

【讨论】:

  • 请注意:Cygwin 使用 NewLib 作为其没有 strptime 的 C 库。
【解决方案2】:

不,Time::Piece strftime/strptime 格式并不总是兼容的。使用较长版本的格式:

my $str = '2003-03-24T13:32:44';
my $f = '%Y-%m-%dT%H:%M:%S';
my $t = Time::Piece->strptime($str, $f);

print "$t\n";

【讨论】:

    猜你喜欢
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多