Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Does anyone know an easy way in Perl to calculate the difference between two timestamps that contain milliseconds? E.g., Start time = 05:07:53.249 Finish time = 05:07:55.401 Difference = 05:07:55.401 - 05:07:53.249

Replies are listed 'Best First'.
Re: time difference in milliseconds
by pg (Canon) on Nov 05, 2004 at 15:52 UTC

    Split on ':' and '.', then convert to measurement in pure-millisecond, then do a minus (assume this is always the same day)

    my $t1 = "05:07:53.249"; my $t2 = "05:07:55.401"; print to_milli($t2) - to_milli($t1); sub to_milli { my @components = split /[:\.]/, shift; return (($components[0] * 60 + $components[1]) * 60 + $components[ +2]) * 1000 + $components[3]; }
Re: time difference in milliseconds
by Prior Nacre V (Hermit) on Nov 05, 2004 at 16:02 UTC

    You could convert to seconds and use the result for your calculations. The conversion is straightforward:

    my ($h, $m, $s) = split /:/, $time; my $time_in_secs = $h * 60 * 60 + $m * 60 * $s;

    Regards,

    PN5

Re: time difference in milliseconds
by osunderdog (Deacon) on Nov 05, 2004 at 19:53 UTC

    Time::HiRes::tv_interval seems to work just fine for this.


    "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.


    OSUnderdog
Re: time difference in milliseconds
by InfiniteLoop (Hermit) on Nov 05, 2004 at 17:12 UTC
    convert both start time and end time to unixtime , use Time::Local.
    Take a diff of the unixtime's. Convert the diff back to days, seconds or whatever you want it to.
Re: time difference in milliseconds
by ikegami (Patriarch) on Nov 05, 2004 at 17:00 UTC
    btw, since you're using padding your fields with 0s, you can use lt (or eq) on their string form if all you really want to do is find the smaller one (or equality). It probably isn't, but just in case.
Re: time difference in milliseconds
by Mutant (Priest) on Nov 05, 2004 at 16:27 UTC
    You might want to look at the tv_interval function of Time::HiRes
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: time difference in milliseconds
by InfiniteLoop (Hermit) on Nov 06, 2004 at 04:08 UTC
    Here is one excellent article on many date/time functions available in perl.