Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse timestamp with millisecond in Perl

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

like image 953
defoo Avatar asked Nov 29 '22 04:11

defoo


2 Answers

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;
like image 197
Pedro Silva Avatar answered Dec 05 '22 22:12

Pedro Silva


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";
like image 28
Chas. Owens Avatar answered Dec 05 '22 21:12

Chas. Owens