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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With