LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl subtract time apaehc access_log (https://www.linuxquestions.org/questions/programming-9/perl-subtract-time-apaehc-access_log-549161/)

noir911 04-26-2007 08:11 AM

Perl subtract time apaehc access_log
 
I need to subtract the date from the first line to the date from the last line in access log to get the total days but I'm not quite sure how. I understand that I need to use localtime() to convert the date in seconds before subtracting. Can anyone give some example? Thanks.

jim mcnamara 04-26-2007 09:05 AM

Try time::local
Code:

$epoch_seconds = timelocal($sec,$min,$hour,$mday,$mon,$year);

taylor_venable 04-26-2007 09:24 AM

You can use the Date::Calc module for this, like so:
Code:

#!/usr/bin/env perl

use warnings;
use strict;

use Date::Calc qw(:all);

my $line1 = '192.168.2.101 - - [14/Feb/2007:09:54:20 -0500] "GET / HTTP/1.1" 200 592 "-" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.1) Gecko/20060601 Firefox/2.0.0.1 (Ubuntu-edgy)"';
my $line2 = '192.168.2.101 - - [30/Mar/2007:20:40:30 -0400] "GET /favicon.ico HTTP/1.1" 404 268 "-" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.7) Gecko/20061022 Iceweasel/1.5.0.7-g2"';

my %month_name = ( 'Jan' => 1,  'Feb' => 2,  'Mar' => 3,
                  'Apr' => 4,  'May' => 5,  'Jun' => 6,
                  'Jul' => 7,  'Aug' => 8,  'Sep' => 9,
                  'Oct' => 10, 'Nov' => 11, 'Dec' => 12  );

$line1 =~ m!\[(\d\d)/(\w\w\w)/(\d\d\d\d):(\d\d):(\d\d):(\d\d) [-+]\d\d\d\d\]!;
my %first = ( 'year'    => $3, 'month'  => $month_name{$2}, 'day'    => $1,
              'hours'  => $4, 'minutes' => $5, 'seconds' => $6);

$line2 =~ m!\[(\d\d)/(\w\w\w)/(\d\d\d\d):(\d\d):(\d\d):(\d\d) [-+]\d\d\d\d\]!;
my %second = ( 'year'    => $3, 'month'  => $month_name{$2}, 'day'    => $1,
              'hours'  => $4, 'minutes' => $5, 'seconds' => $6);

my ($years, $months, $days, $hours, $minutes, $seconds) =
    Date::Calc::Delta_YMDHMS($first{'year'}, $first{'month'}, $first{'day'},
                            $first{'hours'}, $first{'minutes'}, $first{'seconds'},
                            $second{'year'}, $second{'month'}, $second{'day'},
                            $second{'hours'}, $second{'minutes'}, $second{'seconds'});

print "The difference is: ", $years, " years | ", $months, " months | ", $days, " days | ", $hours, " hours | ", $minutes, " minutes | ", $seconds, " seconds\n";

Assuming you haven't changed Apache's logging format for the date.


All times are GMT -5. The time now is 05:41 AM.