在Perl中解析时间戳以毫秒为单位

def*_*foo 4 perl time datetime

假设我有一堆时间戳,如"11/05/2010 16:27:26.003",如何在Perl中用毫秒解析它们.

基本上,我想比较时间戳,看看它们是在特定时间之前还是之后.

我尝试使用Time :: Local,但似乎Time :: Local只能解析秒.另一方面,Time :: HiRes并不是真正用于解析文本的.

谢谢,德里克

Ped*_*lva 15

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;
Run Code Online (Sandbox Code Playgroud)

  • 供参考:http://search.cpan.org/dist/DateTime-Format-Strptime/lib/DateTime/Format/Strptime.pm#STRPTIME_PATTERN_TOKENS (2认同)

Cha*_*ens 9

您可以使用Time::Local并添加.003它:

#!/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";
Run Code Online (Sandbox Code Playgroud)

  • @Derek这是一个正则表达式.`.`匹配任何字符,括号(即`()`)捕获字符串的那一部分,因此正则表达式匹配字符串`$ timestring`捕获我们关心的位(例如小时,分钟,秒等) .)并丢弃我们没有的部分(例如,"/"字符).您可以在[`perldoc perlretut`](http://perldoc.perl.org/perlretut.html)和[`perldoc perlre`](http://perldoc.perl.org/perlre.html)中阅读有关正则表达式的更多信息. (2认同)