Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing time stamps and calculating difference

Tags:

perl

So I am parsing a log file and look for certain time stamps and then subtracting them to get time elapsed.

So I tried a simple code to see if I can use Time::Piece but wasnt successful. My code below:

use Time::Piece;

my ($S, $E);

GetOptions (
    "S=s" => \$S,
    "E=s" => \$E,
    );

my $start    = $S;
my $end = $E;
my %build_time;

my $start_time;
my $end_time;
if(my ($start_time) = $start =~ /\[gg\s+(\d+\:\d+\:\d+)\s+I\]/){
    print"Build_Time: start at $start_time\n";
}
#--------------------
# End time from dj
if(my ($end_time) = $end =~ /\[gg\s+(\d+\:\d+\:\d+)\s+I\]/){
    print "Build_Time: end at $end_time\n";
}

my $difference = Time::Piece->strptime($end_time,'%H:%M:%S') - Time::Piece->strptime($start_time,'%H:%M:%S');

print " difference: $difference \n";

Execute: perl time.pl -S "[gg 8:11:03 I]: Copyright" -E "[gg 8:19:03 I]: BT_DEPTH=99 "

Build_Time: start at 8:11:03 Build_Time: end at 8:19:03 difference: 0

Also what is the time is in 24 hr format and log contains over night run ( so the difference would be negative)?

like image 968
Public Email Avatar asked Jan 21 '26 20:01

Public Email


1 Answers

Your code has a scoping issue: $start_time and $end_time in your if statements mask the outer variables. If the time difference is 23:59:59 max you can use a modulo operation to fix the negative seconds output caused by crossing a date boundary:

time.pl:

use strict;
use warnings;
use Getopt::Long;

use Time::Piece;
my ($S, $E);

GetOptions (
    "S=s" => \$S,
    "E=s" => \$E,
    );

my $start    = $S;
my $end = $E;
my %build_time;

my $start_time;
my $end_time;
if( ($start_time) = $start =~ /\[gg\s+(\d+\:\d+\:\d+)\s+I\]/){
    print"Build_Time: start at $start_time\n";
}
#--------------------
# End time from dj
if( ($end_time) = $end =~ /\[gg\s+(\d+\:\d+\:\d+)\s+I\]/){
    print "Build_Time: end at $end_time\n";
}

my $tp_st = Time::Piece->strptime($start_time,'%H:%M:%S');
my $tp_e =  Time::Piece->strptime($end_time,'%H:%M:%S');

my $difference = $tp_e -$tp_st;
$difference %= 60*60*24; # 1 day
print " difference: $difference \n";

testing:

perl time.pl -S "[gg 8:19:04 I]: Copyright" -E "[gg 8:19:14 I]: BT_DEPTH=99 "
Build_Time: start at 8:19:04
Build_Time: end at 8:19:14
 difference: 10 


perl time.pl -S "[gg 8:19:04 I]: Copyright" -E "[gg 8:19:03 I]: BT_DEPTH=99 "
Build_Time: start at 8:19:04
Build_Time: end at 8:19:03
 difference: 86399 
like image 61
clamp Avatar answered Jan 23 '26 09:01

clamp