Eternal Learner
Eternal Learner

Reputation: 3870

Perl convert microseconds since epoch to localtime

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"

Upvotes: 0

Views: 274

Answers (1)

Grinnz
Grinnz

Reputation: 9231

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

Upvotes: 5

Related Questions