Need help on how to calculate time differences from a list of datetime.
my list of datetime DATA as below, I want to calculate time differences between t1-t2 and following with next line t2 -t1, t1-t2 until the end of list :-
DATA
t1: 2021-Sep-29 18:52:49 - begin here t1(this line)- t1(this line)
t2: 2021-Sep-29 18:52:50 - t1(above line) -t2 (this Line)
t1: 2021-Oct-08 16:09:36 -t2 (above line) - t1 (this line)
t2: 2021-Oct-08 16:49:23 - t1 (above line) - t2 (this line(
t1: 2021-Oct-08 16:55:01
t2: 2021-Oct-08 17:00:00
....
...
...
tn:2021-Nov-11 12:36:40
expected output
t1: 2021-Sep-29 18:52:49
time: 0 seconds
t2: 2021-Sep-29 18:52:50
time: 1 seconds
t1: 2021-Oct-08 16:09:36
time: 1 seconds
t2: 2021-Oct-08 16:49:23
time : 767,806 seconds
t1: 2021-Oct-08 16:55:01
time : 338 seconds
t2: 2021-Oct-08 17:00:00
time : 299 seconds
....
my script as below , I've tried to split all data into array of t1 & t2 and calculate time difference of t1-t2.
use Time::Piece;
my $file = './tmp/compiled/AllData_process.tmp';
open(OUT, ">" ,"tmp/compiled/AllData_compute.tmp") or die "Couldn't open file $!";
open (DATA, $file )or die "Couldn't open file $file, $!";
@compute = <DATA>;
foreach $compute(@compute){
chomp $compute;
if ($compute =~ s/t1://){
push (@t1, $compute);
for ($a = 0; $a < $#t1; $a = $a 1){
}
print OUT "$t1[$a]\n";
}
if ($compute =~ s/t2://){
push (@t2, $compute);
for ($a = 0; $a < $#t2; $a = $a 1){
}
print OUT "$t2[$a]\n";
}
my $timediff = time_difference($t1[$a],$t2[$a]);
print OUT "$timediff\n";
}
sub time_difference {
my $date_format = '%Y-%b-%d %H:%M:%S';
my ($beg, $end) = map Time::Piece->strptime($_,$date_format), @_;
($end-$beg)->seconds;
}
Output
t1: 2021-Sep-29 18:52:49
t2: 2021-Sep-29 18:52:50
time: 1 seconds
t1: 2021-Oct-08 16:09:36
t2: 2021-Oct-08 16:49:23
time : 2387 seconds
t1: 2021-Oct-08 16:55:01
t2: 2021-Oct-08 17:00:00
time : 299 seconds
....
thanks in advance
CodePudding user response:
use 5.014;
use warnings;
use Time::Piece qw( );
sub parse_time { Time::Piece->strptime($_[0], '%Y-%b-%d %H:%M:%S')->seconds }
my $prev;
while (<>) {
say;
s/^[^:]*:\s*//;
my $time = parse_time($_);
if ($prev) {
my $diff = $time - $prev;
say "time: $diff seconds";
}
$prev = $time;
}