What is the best way to handle the math of time in Perl?

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

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

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

Are there any good designs to work with time in Perl? I do not want to do the math of time, if I can avoid it.

+6
time perl
source share
2 answers

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 get the results.

+13
source share

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 the math with the date with the subtraction. This is the only way to get a “stopwatch duration” from two dates, and only the stopwatch duration has ever been useful for the date arithmetic I am doing. The DateTime :: Duration interface is confusing and misleading, especially if you think you have a stopwatch and you don’t.

People used to mention how this would be incomprehensible, but it was never corrected.

The Time :: Piece module makes a nice alternative. I would say that overall it is not as useful as DateTime, but it definitely avoids such confusion. I prefer DateTime, but hardly.

+5
source share

All Articles