How can I use Perl to compare datetime and calculate deltas?

I extracted the year, month, day, hour, minute, second and millisecond data from human readable text (it was not in timeline format, but rather like "X started with HH: MM: SS.SSS on DD MMM YYYY and ended HH: MM: SS.SSSS on DD MMM YYYY "), so for every event recorded, I have each of the values.

However, I need to turn them into some kind of timestamp so that I can do math on it - I want to determine how long the event lasted (end time - start time). I was hoping the function time

would take parameters, so I can create two arbitrary time

s, but that doesn't seem to be the case.

If possible, I would like to stick to the functionality available in the core Perl libraries or scripts that I can add to the project, as getting the CPAN modules installed on the target computers would be just a headache for everyone, if it is even possible to get the modules via security restrictions.

+2


source to share


5 answers


You can do this with Time: Local . This is basically the flip side of the "localtime" builtin function, so you can create a timestamp from a standard date.



+3


source


You need the CPAN DateTime module . Here's an introduction.

On a Debian GNU / Linux or Ubuntu system, simply run:



apt-get install libdatetime-perl

      

to install the module.

+7


source


In terms of built-in modules, they can be useful:

Thus, time and date calculations are tricky. If the only hurdle is a few headaches installing modules (and not a company policy prohibiting them), then I would really recommend looking at CPAN.

Edit . From your comment on another post, it can be seen that there are restrictions for companies. You should update your original post as there is a big difference between "headaches" and "security restrictions". In any case, DateTime

and Date::Manip

worth a look. Even if you don't install them, you can learn a lot from your source.

+2


source


If you were only interested in the comparison time,

my $ts1 = sprintf( '%4.4d%2.2d%2.2d%2.2d%2.2d%3.3d', 
                   $year1, $month1, $mday1, $hour1, $min1, $sec1, $ms1 );

      

to

my $ts2 = sprintf( '%4.4d%2.2d%2.2d%2.2d%2.2d%3.3d', 
                   $year2, $month2, $mday2, $hour2, $min2, $sec2, $ms2 );

      

with help cmp

will suffice.

To do arithmetic at this time, use Time :: Local to get the seconds from the epoch and then add $ms1/1000

to that value.

my $time1 = timelocal($sec1, $min1, $hour1, $mday1, $mon1, $year1) + $ms1/1000;

      

+2


source


You can use POSIX::mktime

to include the stakeout time in the timestamp. Keep in mind that month is 0 based and year is 1900 based, so adjust accordingly. :-)

use POSIX qw(mktime);
$timestamp = mktime($sec, $min, $hour, $day, $month - 1, $year - 1900);

      

+1


source







All Articles