【问题标题】:convert perl timestamp to human readable将 perl 时间戳转换为人类可读
【发布时间】:2014-06-24 18:28:30
【问题描述】:

我正在阅读一个日志文件,其中包含我想要转换为人类可读的时间戳。 在此命令中,$1 包含一个时间戳(如 1403457192.663): $temp = localtime->mon($1) 但不是存储月份,$temp 包含与输入相同的时间戳。我做错了什么?

【问题讨论】:

    标签: perl timestamp


    【解决方案1】:

    你已经接近了。时间应该传递给localtime 函数,而不是mon 方法。:

    $temp = localtime($1)->mon; # 6
    

    您可以使用strftime 将其转换为任意格式

    localtime($1)->strftime("%b %d %a"); # Jun 22 Sun
    

    或者,如果您对格式不挑剔,您可以将其字符串化:

    $temp = localtime($1);
    print "$temp\n"; # Sun Jun 22 13:13:12 2014
    

    这假设 Time::Piece 已加载。

    【讨论】:

    • 你呢strftime
    • 我正在使用 Time::localtime; ...这似乎工作...还是我应该使用 Time::Piece ?
    【解决方案2】:

    我会选择的

    $ perl -E'
       use POSIX qw( strftime );
       say strftime("%Y/%m/%d %H:%M:%S", localtime(1403457192.663));
    '
    2014/06/22 13:13:12
    

    但您使用的是 Time::localtime。该模块覆盖了 localtime 内置模块,因此如果使用它,则需要稍作修改。

    要么避免使用 Time::localtime 的localtime

    $ perl -E'
       use POSIX           qw( strftime );
       use Time::localtime qw( localtime );
       say strftime("%Y/%m/%d %H:%M:%S", CORE::localtime(1403457192.663));
    '
    2014/06/22 13:13:12
    

    或展平现有的 Time::localtime 对象。

    $ perl -E'
       use POSIX           qw( strftime );
       use Time::localtime qw( localtime );
       my $tm = localtime(1403457192.663);
       say strftime("%Y/%m/%d %H:%M:%S", @$tm);
    '
    2014/06/22 13:13:12
    

    所有这些解决方案都失去了毫秒精度。如果相关,您必须从原始输入中提取它并将其重新插入到输出中。

    【讨论】:

      【解决方案3】:

      对于格式化日期,大多数系统 strftime 手册页将列出一些“快捷方式”,以获得某些“标准”格式。

      例如 %F 等同于 “%Y-%m-%d”

      ~/% perl -MPOSIX -E'say strftime"%D",localtime'
      06/25/14
      ~/% perl -MPOSIX -E'say strftime"%F",localtime'
      2014-06-25
      

      这些可以使使用“ye olde”strftime 更容易;-)

      【讨论】:

        【解决方案4】:

        从 5.10 开始的 Perl 现在包含 Time::Piece。这使它成为在 Perl 中处理时间的官方方式。或者,与 Perl 中的某些东西一样官方。由于它始终可用,您不妨学习使用它:

        use strict;
        use warnings;
        use Time::Piece;
        use Time::Seconds;   # More time fun!
        
        my $time = Time::Piece->new;   # Gets the current timestamp
        
        my $month = $time->mon();          # Month from 1 to 12
        my $month = $time->month();        # Abbreviation of the name of month
        my $month = $time->fullmonth();    # Full name of the month
        my $time = $time + (ONE_DAY * 30)  # Add thirty days to the time
        my $date = $time->mdy              # The date 30 days from now.
        

        【讨论】:

        • 核心模块的存在并不意味着推荐使用它。事实上,我强烈建议不要使用 Time::Seconds。在没有意识到的情况下错误地使用它非常容易,因为它会迫使您编写看起来不正确的代码。 (一天的秒数不是恒定的。)
        猜你喜欢
        • 2021-03-14
        • 1970-01-01
        • 1970-01-01
        • 2012-04-19
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 2012-11-12
        • 1970-01-01
        相关资源
        最近更新 更多