parse timestamp with millisecond in Perl

14,090

Solution 1

You can use Time::Local and just add the .003 to it:

#!/usr/bin/perl

use strict;
use warnings;

use Time::Local;

my $timestring = "11/05/2010 16:27:26.003";
my ($mon, $d, $y, $h, $min, $s, $fraction) =
    $timestring =~ m{(..)/(..)/(....) (..):(..):(..)([.]...)};
$y -= 1900;
$mon--;

my $seconds = timelocal($s, $min, $h, $d, $mon, $y) + $fraction;

print "seconds: $seconds\n";
print "milliseconds: ", $seconds * 1_000, "\n";

Solution 2

use DateTime::Format::Strptime;

my $Strp = new DateTime::Format::Strptime(
    pattern => '%m/%d/%Y %H:%M:%S.%3N',
    time_zone   => '-0800',
);

my $now = DateTime->now;
my $dt  = $Strp->parse_datetime('11/05/2010 23:16:42.003');
my $delta = $now - $dt;

print DateTime->compare( $now, $dt );
print $delta->millisecond;
Share:
14,090
defoo
Author by

defoo

Updated on June 08, 2022

Comments

  • defoo
    defoo about 2 years

    Assuming I have a bunch of timestamps like "11/05/2010 16:27:26.003", how do parse them with millisecond in Perl.

    Essentially, I would like to compare the timestamp to see if they are before or after a specific time.

    I tried using Time::Local, but it seems that Time::Local is only capable to parse up second. And Time::HiRes, on the other hand, isn't really made for parsing text.

    Thanks, Derek