perl POSIX::strptime - my data looks like 9:31:00 AM - I want to extract the minute and perform a calculation
I want to extract the minute from a specified time that exists in the 2nd column of a comma delimited file and perform a calculation. The format of the time is as follows:
9:31:00 AM
I want to extract the minute value and calculate the total minutes in the day so far. I do this in subroutine get_time. But the returned开发者_运维百科 value is always zero which makes me think that I am not using POSIX::strptime correctly. Any insight would be wonderful. Thank you.
#!/usr/bin/env perl
use strict;
use POSIX::strptime;
use Text::CSV;
sub get_time
{
my($str) = @_;
my ($sec, $min, $hour) = (POSIX::strptime($str, '%I:%M:%S')) [3,4,5];
print "$hour\n";
return($hour*60 + $min)
}
open my $fh, "<", datafile.txt
my $csv = Text::CSV->new() or die "Failed to create Text::CSV object";
my $line = <$fh>;
die "Failed to parse line <<$line>>\n\n" unless $csv->parse($line);
my @columns = $csv->fields();
while ($line = <$fh>)
{
chomp $line;
die "Failed to parse line <<$line>>\n\n" unless $csv->parse($line);
my @columns = $csv->fields();
die "Insufficient columns in <<$line>>\n" if scalar(@columns) < 1;
my $minute = get_time($columns[1]);
print "$minute\n";
}
In get_time, you have the line
my ($sec, $min, $hour) = (POSIX::strptime($str, '%I:%M:%S')) [3,4,5];`
According to the docs, strptime returns
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = POSIX::strptime("string", "Format");
So it looks like you need
my ($sec, $min, $hour) = (POSIX::strptime($str, '%I:%M:%S')) [0,1,2];
instead.
Best of luck!
It's impossible to correctly determining the number of a minutes in a day before a certain time without knowing the time zone and possibly the date.
$ perl -MDateTime -E'
for (10..16) {
my $dt = DateTime->new(
year => 2011,
month => 3,
day => $_,
hour => 9,
minute => 31,
second => 0,
time_zone => "America/New_York",
);
( my $ref_dt = $dt->clone )->truncate(to => "day");
my $minutes = ($dt - $ref_dt)->in_units("minutes");
say($dt->ymd, " ", $minutes);
}
'
2011-03-10 571
2011-03-11 571
2011-03-12 571
2011-03-13 511 <------
2011-03-14 571
2011-03-15 571
2011-03-16 571
精彩评论