我刚刚去了perl。我试图从以
开头的文本文件中的一行中提取日期和时间日期:05 / Feb / 2017 21:30:00 PST - 06 / Feb / 2017 06:00:00 PST
我已设法清除脚本,但我试图修改它,以便将上面的内容提取到
start date - 2017-02-05 21:30:00
end date - 2017-02-06 06:00:00
任何帮助将不胜感激
#Is it a reg date
} elsif (!$start && $line[$i] =~ /^Date: (.+?) - (.+)$/i) {
$regstartdate = $1;
$regenddate = $2;
} elsif (!$start && $line[$i] =~ /^Date: (.+)$/i) {
#Monday 3rd July 2006
#Friday 30th June 2006 01:00 Hrs EST
$regstartdate = $1;
eval{
$start = &dateconv($regstartdate);
$end = $start;
1;
}
or do{
warn "Could not process start date: $regstartdate";
};
} elsif (!$start && $line[$i] =~ /^Time:\s*(\d+:\d+)[\s\-]+\s+(\d+:\d+)\s+[hH][rR][sS]\s+(\w+)$/i) {
$tz = $3;
$twestartdate = $regstartdate . " ".$1." Hrs ".$3;
$tweenddate = $regenddate . " ".$2." Hrs ".$3;
$start = &dateconv($regstartdate);
$end = &dateconv($regenddate);
} elsif (!$start && $line[$i] =~ /^Time:\s*(\d+:\d+)[\s*\-]+\s*(\d+:\d+)\s+(\w+)$/i) {
$tz = $3;
$regstartdate = $regstartdate . " ".$1." Hrs ".$3;
$regenddate = $regenddate . " ".$2." Hrs ".$3;
$start = &dateconv($regstartdate);
$end = &dateconv($regenddate);
#Is it a reg Time
} elsif (!$start && $line[$i] =~ /^Interruption Time: (\d+:\d+)[\s\-]+(\d+:\d+) (\w+)/i) {
$regstartdate = $regstartdate . " " . $1 . " Hrs " . $3;
$regenddate = $regenddate . " " . $2 . " Hrs " . $3;
$start = &dateconv($regstartdate);
$end = &dateconv($regenddate);
#Is is the start time ?
} elsif (!$start && $line[$i] =~ /^Duration:\s*START DATE (.*)/i) {
$start = &dateconv($1);
#Is it the end time ?
} elsif (!$end && $line[$i] =~ /^END DATE (.*)/i) {
my $endtime = $1;
$end = &dateconv($endtime);
$endtime =~ m/(\w{1,2}ST)/g;
$tz = $1;
答案 0 :(得分:2)
使用我更喜欢的Time::Piece
提供解决方案 - 因为我喜欢这个界面,但也因为它是perl 5.9.5的核心
#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $input_format = '%d/%b/%Y %H:%M:%S';
my $output_format = '%Y-%m-%d %H:%M:%S';
while (<DATA>) {
if ( my ( $start_str, $end_str ) = m/Date: (.*) PST - (.*) PST/ ) {
my $start = Time::Piece->strptime( $start_str, $input_format );
my $end = Time::Piece->strptime( $end_str, $input_format );
print "Start:\t", $start->strftime($output_format), "\n";
print "End: \t", $end ->strftime($output_format), "\n";
}
}
__DATA__
Date: 05/Feb/2017 21:30:00 PST - 06/Feb/2017 06:00:00 PST
我喜欢它的原因是因为上面的$start
和$end
是&#39;时间对象&#39;所以你可以做以下事情:
print $start -> epoch;
print "Elapsed time: ", $end - $start, "s\n";
答案 1 :(得分:0)
如果您使用DateTime模块,解析和格式化这些日期字符串是微不足道的:
use strict;
use warnings;
use 5.010;
use DateTime;
use DateTime::Format::Strptime;
my $fmt = DateTime::Format::Strptime->new(pattern => '%d/%b/%Y %H:%M:%S');
my $line = 'Date: 05/Feb/2017 21:30:00 PST - 06/Feb/2017 06:00:00 PST';
$line =~ s/^Date: //;
my @dates = split(/\s*-\s*/, $line);
for my $date (@dates) {
my $dt = $fmt->parse_datetime($date);
say $dt->ymd . ' ' . $dt->hms;
}
产地:
2017-02-05 21:30:00
2017-02-06 06:00:00
您可以根据需要调整格式。