【问题标题】:Time::Piece strptime has trouble with %XTime::Piece strptime 与 %X 有问题
【发布时间】:2022-02-22 03:25:09
【问题描述】:

我正在尝试在 perl v5.26 中使用 Time::Piece->strptime() 解析以下数据:

my $str = "Mon Feb 21 02:54:49 IST 2022";
my $time_zone = substr($str, 20, 3);
my $date_time = Time::Piece->strptime($str, "%a %b %e %X $time_zone %Y");
print "Todays date/time is : $date_time";

但是,当我执行上面的代码 sn-p 时,我得到了以下错误:

Error parsing time at /usr/local/lib64/perl5/Time/Piece.pm line 598.

我不确定我错过了什么,任何帮助都会非常有帮助。

【问题讨论】:

    标签: date perl strptime


    【解决方案1】:

    %X 没有最后的AM/PM 只能在字符串的末尾起作用。

    my $str = "Mon Feb 21 IST 2022 02:54:49";
    my $time_zone = substr($str, 11, 3);
    warn $time_zone;
    my $date_time = Time::Piece->strptime($str, "%a %b %e $time_zone %Y %X");
    print "Todays date/time is : $date_time";
    

    my $str = "Mon Feb 21 02:54:49 AM IST 2022";
    my $time_zone = substr($str, 23, 3);
    my $date_time = Time::Piece->strptime($str, "%a %b %e %X $time_zone %Y");
    print "Todays date/time is : $date_time";
    

    但我的测试表明这种行为取决于 Perl 版本,所以可能根本不要使用 %X(与 %I:%M:%S %p 相同)并切换到 %T(与 %H:%M:%S 相同)。

    my $str = "Mon Feb 21 02:54:49 IST 2022";
    my $time_zone = substr($str, 20, 3);
    my $date_time = Time::Piece->strptime($str, "%a %b %e %T $time_zone %Y");
    print "Todays date/time is : $date_time";
    

    【讨论】:

    • 我最终使代码与 my $date = Time::Piece->strptime($str, "%a %b %d %T %Y"); But 一起工作。如果我添加 $time_zone,比如my $date = Time::Piece->strptime($str, "%a %b %d %T $time_zone %Y");,它不会打印时区。我们能做些什么吗?
    • 如果您有其他问题,请提出新问题。您可以链接到旧的以获取上下文。
    猜你喜欢
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 2014-11-24
    • 2011-01-02
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多