Perl convert microseconds since epoch to localtime

℡╲_俬逩灬. 提交于 2019-12-14 04:03:39

问题


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;

Eg: "Input = 1555329743301750 (microseconds since epoch) Output = 070223.301750"


回答1:


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 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";

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";

(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.)



来源:https://stackoverflow.com/questions/56384965/perl-convert-microseconds-since-epoch-to-localtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!