perl POSIX::strptime - 我的数据看起来像上午 9:31:00 - 我想提取分钟并执行计算
我想从逗号分隔文件第二列中存在的指定时间中提取分钟并执行计算。时间的格式如下:
9:31:00 AM
我想提取分钟值并计算迄今为止一天中的总分钟数。我在子例程 get_time 中执行此操作。但返回值始终为零,这让我认为我没有正确使用 POSIX::strptime 。任何见解都会很棒。谢谢。
#!/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";
}
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";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 get_time 中,您有以下行
根据 docs, strptime 返回
所以看起来您
需要。
祝你好运!
In get_time, you have the line
According to the docs, strptime returns
So it looks like you need
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.