tags:

views:

587

answers:

2

I am running through two large log files and I want to compare timestamps.

I already wrote a Perl script to find the matching log statements, but I need to find the difference in the timestamps.

For example, 15:31:19.430888 minus 15:31:19.427763

Are there any good constructs for dealing with time in Perl? I don't want to deal with time math myself if I can avoid it.

+12  A: 

You can use the DateTime CPAN module.

eg.

my $dt = DateTime->new( 
                      year   => 2009,
                      hour   => 15,
                      minute => 31,
                      second => 19,
                      nanosecond => 430888
);
my $dt2 = DateTime->new( 
                      year   => 2009,
                      hour   => 15,
                      minute => 31,
                      second => 19,
                      nanosecond => 427763
);
my $duration = $dt - $dt2;

which will give you a DateTime::Duration object to retrieve the results from.

denkfaul
Is there any such construct in the defaul perl lib? Not in CPAN?
windfinder
@windfinder: I don't believe that there is. Perl comes with a fairly limited set of default libs.
R. Bemrose
wordfinder, in case you didn't see below, Time::Piece is in the core libs in the latest Perl. I don't think that's a good enough reason to use something, in general, but Time::Piece is pretty good.
skiphoppy
+4  A: 

DateTime is the best, but only if you remember to use the subtract_datetime_absolute method instead of the overloaded minus operator when you do any date math involving subtraction. This is the only way to get a "stopwatch duration" out of two datetimes, and only the stopwatch duration has ever been useful for the kind of date arithmetic I do. The DateTime::Duration interface is confusing and misleading, especially when you think you have a stopwatch duration and you don't.

People mentioned early on how confusing this was going to be but it was never corrected.

The Time::Piece module makes a nice alternative. I'd have to say that overall it is not as useful as DateTime, but it definitely avoids this kind of confusion. I prefer DateTime, but just barely.

skiphoppy
Time::Piece also comes with 5.10 for the "I only want core modules" crowd. Usually a misguided desire, but I thought I'd mention it.
Schwern