georgetovrea
georgetovrea

Reputation: 577

how to extract 5minutes records from specific datetime from txt?

Trying to find use perl or simple way for get 5 minutes events( from 19:25:00) and write to other txt file,

files are in form :

10.10.10.1,10.10.10.2,6000,1433,2019-02-28,19:28:00.178,0.000,6,....S.,212,1,40,1    
10.10.10.1,10.10.10.2,6000,1433,2019-02-28,19:28:00.178,0.000,6,....S.,212,1,40,1
10.10.10.1,10.10.10.2,6000,1433,2019-02-28,19:29:00.178,0.000,6,....S.,212,1,40,1
10.10.10.1,10.10.10.2,6000,1433,2019-02-28,19:32:00.180,0.000,6,....S.,212,1,40,1

the results I want is ,

10.10.10.1,10.10.10.2,6000,1433,2019-02-28,19:28:00.178,0.000,6,....S.,212,1,40,1    
10.10.10.1,10.10.10.2,6000,1433,2019-02-28,19:28:00.178,0.000,6,....S.,212,1,40,1
10.10.10.1,10.10.10.2,6000,1433,2019-02-28,19:29:00.178,0.000,6,....S.,212,1,40,1

my code ,

use strict;
use warnings;
use DateTime     qw( );
use Text::CSV_XS qw( );

open my $fh, '<', 'in.csv';
open my $fo, '>', 'out.txt';
my $dt = DateTime->now( time_zone => 'local' );
$dt->subtract( minutes => 5 );
my $start_date = $dt->strftime("2019-02-28");
my $start_time = $dt->strftime("17:31:22.000");

my $csv = Text::CSV_XS->new({ auto_diag => 2, binary => 1 });
while ( my $row = $csv->getline($fh) ) {
    next
       if $row->[4] < $start_date
       || $row->[4] == $start_date && $row->[5] < $start_time;

      $csv->say($fh, $row);
}

but get the error messgae as below,

Argument "2019-02-28" isn't numeric in numeric lt (<) 
Argument "11:59:57.023" isn't numeric in numeric lt (<) 

Upvotes: 1

Views: 49

Answers (1)

ikegami
ikegami

Reputation: 385915

use DateTime     qw( );
use Text::CSV_XS qw( );

my $dt = DateTime->now( time_zone => 'local' );
$dt->subtract( minutes => 5 );
my $start_date = $dt->strftime("%Y-%m-%d");
my $start_time = $dt->strftime("%H:%M:%S");

my $csv = Text::CSV_XS->new({ auto_diag => 2, binary => 1 });
while ( my $row = $csv->getline($fh_in) ) {
    next
       if $row->[4] lt $start_date
       || $row->[4] eq $start_date && $row->[5] lt $start_time;

    $csv->say($fh_in, $row);
}

Upvotes: 1

Related Questions