Perl将自纪元以来的微秒转换为本地时间 [英] Perl convert microseconds since epoch to localtime
问题描述
在perl中,自纪元以来以微秒为单位,我如何以
In perl, given microseconds since epoch how do I convert to localtime in a format like
my $time = sprintf "%02ld,%02ld,%02ld.%06ld", $hour, $min, $sec, $usec;
例如:输入= 1555329743301750(自历元以来的微秒数)输出= 070223.301750
Eg: "Input = 1555329743301750 (microseconds since epoch) Output = 070223.301750"
推荐答案
核心 Time :: Piece 可以进行转换,但是它不能处理亚秒级的数据,因此您需要自己处理。
The core Time::Piece can do the conversion, but it doesn't handle subseconds so you'd need to handle those yourself.
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偏移,我们可以使用时间:: Moment :: Role :: TimeZone 。
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 较重,但可以自然处理所有内容,至少达到微秒级的精度。
Finally, DateTime is a bit heavier but can handle everything naturally, at least to microsecond precision.
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,'。')
所以它只是一个字符串操作如果您确定它将采用字符串形式,则转到模块,但在这种规模下,这不太可能成为问题。)
(To avoid possible floating point issues, you could replace my $sec = $input / 1000000
with substr(my $sec = $input, -6, 0, '.')
so it's purely a string operation until it goes to the module, if you are sure it will be in that string form - but it's unlikely to be an issue at this scale.)
这篇关于Perl将自纪元以来的微秒转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!