2010-11-08 123 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

相關問題