Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

How to compare time in perl

by abhishes (Friar)
on Feb 08, 2003 at 17:41 UTC ( #233746=perlquestion: print w/ replies, xml ) Need Help??
abhishes has asked for the wisdom of the Perl Monks concerning the following question:

Hello Perl Monks!

I am parsing a file where I find strings of the following pattern 2003/02/05 17:32:06.179

I am able to extract the year, month, day, hour, minute, second and millisecond from this string using a regular expression.

But if I have two such strings how to find out which of the two is smaller. Is there a speedy way to compare two such strings for time.

Thanks for your help in advance.

regards,
Abhishek.

Comment on How to compare time in perl
Re: How to compare time in perl
by Nitrox (Chaplain) on Feb 08, 2003 at 17:46 UTC
    Use the site's search to take a peek at existing nodes that cover this.

    -Nitrox

Re: How to compare time in perl
by valdez (Monsignor) on Feb 08, 2003 at 17:48 UTC

    You can use Date::Calc to parse time strings and compare them.

    Ciao, Valerio

Re: How to compare time in perl
by mojotoad (Monsignor) on Feb 08, 2003 at 18:39 UTC
    You don't have to parse the dates. Since the strings are a) constant width and consistently formatted, and b) organized left-to-right in order of granularity, you can simply use a string comparison. Like so:

    #!/usr/bin/perl @data = <DATA>; chomp @data; foreach (sort { $a cmp $b } @data) { print "$_\n"; } __END__ 2003/02/05 17:32:06.179 2003/02/05 17:32:06.159 2003/01/05 17:32:06.179 1999/01/05 17:32:06.179
    When run this prints:
    1999/01/05 17:32:06.179 2003/01/05 17:32:06.179 2003/02/05 17:32:06.159 2003/02/05 17:32:06.179

    Matt

      The equal width and 0 packing of single digits is vital as this will choke cmp:

      2003/02/05 2:32:06.179 2003/02/05 17:32:06.179 2003/02/05 20:32:06.159
      cheers

      tachyon

      s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

        Even if they aren't to begin with he can normalize them first:
        $time=~s{ #$1 $2 $3 $4 $5 $6 $7 (\d+)/(\d+)/(\d+)\s+(\d+):(\d+):(\d+)\.(\d+) } { sprintf '%04d/%02d/%02d %02d:%02d:%02d.%3d', $1, $2, $3, $4, $5, $6, $7 }xe or die "Failed to normalize '$time'\n";

        --- demerphq
        my friends call me, usually because I'm late....

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://233746]
Approved by mattriff
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2014-12-25 21:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (163 votes), past polls