Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to deal with time math in Perl?

Tags:

time

perl

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.

like image 698
Alex Avatar asked Mar 05 '09 16:03

Alex


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 retrieve the results from.

like image 158
denkfaul Avatar answered Nov 18 '22 08:11

denkfaul


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.

like image 34
skiphoppy Avatar answered Nov 18 '22 10:11

skiphoppy