2010-11-08 119 views
3

假设我有一堆像“11/05/2010 16:27:26.003”这样的时间戳,怎么在毫秒中用Perl解析它们。以毫秒为单位解析Perl的时间戳

本质上,我想比较时间戳,看他们是否在特定时间之前或之后。

我试过使用Time :: Local,但似乎Time :: Local只能解析第二个。另一方面,Time :: HiRes并非真正用于解析文本。

感谢, 德里克

回答

8

您可以使用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"; 
+0

遗憾的看似琐碎的问题。我对perl非常陌生。我想知道“$ timestring =〜m {.....”这行的目的是什么? – defoo 2010-11-08 19:32:24

+1

@Derek这是一个正则表达式。 '.'匹配任何字符和括号(即'()')捕获字符串的那部分,因此正则表达式匹配字符串'$ timestring',捕获我们关心的位(例如小时,分钟,秒等等。)并放弃我们不需要的部分(例如,“/”字符)。您可以在['perldoc perlretut'](http://perldoc.perl.org/perlretut.html)和['perldoc perlre'](http://perldoc.perl.org/perlre.html)中阅读更多有关正则表达式的内容。 – 2010-11-08 19:46:44

+0

感谢您的解释 – defoo 2010-11-08 19:51:11

12
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; 
+2

并仅供参考:http://search.cpan.org/dist/DateTime-Format-Strptime/lib/DateTime/Format/Strptime.pm#STRPTIME_PATTERN_TOKENS – 2013-12-03 06:02:25

相关问题