Perl 将自纪元以来的微秒数转换为本地时间
Perl convert microseconds since epoch to localtime
在 perl 中,给定自纪元以来的微秒,我如何以
这样的格式转换为本地时间
my $time = sprintf "%02ld,%02ld,%02ld.%06ld", $hour, $min, $sec, $usec;
例如:"Input = 1555329743301750 (microseconds since epoch) Output = 070223.301750"
核心 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 provides a nicer option for dealing with subseconds, but needs some help to find the UTC offset for the arbitrary time in system local time, we can use 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, '.')
,因此在进入模块之前它只是一个字符串操作,如果您确定它会在该字符串中形式 - 但在这种规模下不太可能成为问题。)
在 perl 中,给定自纪元以来的微秒,我如何以
这样的格式转换为本地时间my $time = sprintf "%02ld,%02ld,%02ld.%06ld", $hour, $min, $sec, $usec;
例如:"Input = 1555329743301750 (microseconds since epoch) Output = 070223.301750"
核心 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 provides a nicer option for dealing with subseconds, but needs some help to find the UTC offset for the arbitrary time in system local time, we can use 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, '.')
,因此在进入模块之前它只是一个字符串操作,如果您确定它会在该字符串中形式 - 但在这种规模下不太可能成为问题。)