【问题标题】:Perl convert microseconds since epoch to localtimePerl 将自纪元以来的微秒转换为本地时间
【发布时间】:2019-10-16 12:08:49
【问题描述】:

在 perl 中,给定自纪元以来的微秒,我如何以类似

的格式转换为本地时间
my $time = sprintf "%02ld,%02ld,%02ld.%06ld", $hour, $min, $sec, $usec;

例如:“输入 = 1555329743301750(自纪元以来的微秒)输出 = 070223.301750”

【问题讨论】:

    标签: perl epoch


    【解决方案1】:

    核心Time::Piece 可以进行转换,但它不处理亚秒级,因此您需要自己处理。

    use strict;
    use warnings;
    use Time::Piece;
    my $input = '1555329743301750';
    my ($sec, $usec) = $input =~ m/^([0-9]*)([0-9]{6})$/;
    my $time = localtime($sec);
    print $time->strftime('%H%M%S') . ".$usec\n";
    

    Time::Moment 为处理亚秒提供了更好的选择,但需要一些帮助才能找到系统本地时间中任意时间的 UTC 偏移量,我们可以使用Time::Moment::Role::TimeZone

    use strict;
    use warnings;
    use Time::Moment;
    use Role::Tiny ();
    my $input = '1555329743301750';
    my $sec = $input / 1000000;
    my $class = Role::Tiny->create_class_with_roles('Time::Moment', 'Time::Moment::Role::TimeZone');
    my $time = $class->from_epoch($sec, precision => 6)->with_system_offset_same_instant;
    print $time->strftime('%H%M%S%6f'), "\n";
    

    最后,DateTime 有点重,但可以自然地处理所有事情,至少可以达到微秒级的精度。

    use strict;
    use warnings;
    use DateTime;
    my $input = '1555329743301750';
    my $sec = $input / 1000000;
    my $time = DateTime->from_epoch(epoch => $sec, time_zone => 'local');
    print $time->strftime('%H%M%S.%6N'), "\n";
    

    (为避免可能出现的浮点问题,您可以将 my $sec = $input / 1000000 替换为 substr(my $sec = $input, -6, 0, '.'),因此它只是一个字符串操作,直到它进入模块,如果您确定它将采用该字符串形式 - 但不太可能在这种规模上是一个问题。)

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2013-03-02
      • 2015-12-22
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 2010-09-13
      相关资源
      最近更新 更多