需要有關如何從日期時間串列計算時差的幫助。
我的日期時間資料串列如下,我想計算 t1-t2 和下一行 t2 -t1, t1-t2 之間的時間差,直到串列結束:-
資料
t1: 2021-Sep-29 18:52:49 - 從這里開始 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 (線上) - t1 (這條線) t2: 2021-Oct-08 16:49:23 - t1 (線上) - t2 (這條線(
t1) : 2021-Oct-08 16:55:01
t2: 2021-Oct-08 17:00:00
....
...
...
tn:2021-Nov-11 12:36:40
預期輸出
t1:2021-Sep-29 18:52:49
時間:0 秒
t2:2021-Sep-29 18:52:50
時間:1 秒
t1:2021-Oct-08 16:09:36
時間:1 秒
t2: 2021-Oct-08 16:49:23
時間 : 767,806 秒
t1: 2021-Oct-08 16:55:01
時間 : 338 秒
t2: 2021-Oct-08 17:00:00
秒
. 2 ..
我的腳本如下,我嘗試將所有資料拆分為 t1 和 t2 陣列并計算 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;
}
輸出
t1: 2021-Sep-29 18:52:49
t2: 2021-Sep-29 18:52:50
時間: 1 秒
t1: 2021-Oct-08 16:09:36
t2: 2021-Oct-08 16: 49:23
時間 : 2387 秒
t1: 2021-Oct-08 16:55:01
t2: 2021-Oct-08 17:00:00
時間 : 299 秒
....
提前致謝
uj5u.com熱心網友回復:
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/369526.html
