我有示例 CSV 数据文件,其中包含 100 万条记录和 1 个日期 (14/03/2017 00:11:17)。我需要从此示例 CSV 文件生成 6 个月的数据。 Bash 脚本需要 20 分钟才能生成 1 天的数据。
数据样本
- '12/01/2017 03:22:17,样本数据,1234,样本,123455,67546464'
预期结果
'01/01/2017 03:22:17,样本数据,1234,样本,123455,67546464'
'02/01/2017 03:22:17,样本数据,1234,样本,123455,67546464'
到
'30/01/2017 03:22:17,样本数据,1234,样本,123455,67546464'
答案1
cat 6months.pl
#!/usr/bin/env perl
use Text::CSV;
use DateTime;
use DateTime::Format::Strptime;
use autodie qw/ open close /;
my $csv = Text::CSV->new({binary => 1, quote_space => 0});
my $dateparser = DateTime::Format::Strptime->new(pattern => "%d/%m/%Y %T", time_zone => "local");
for my $file (@ARGV) {
open my $fh, '<', $file;
while (my $row = $csv->getline($fh)) {
my $datestr = shift @$row;
my $date = $dateparser->parse_datetime($datestr)->truncate(to => month);
my $end = $date->clone->add(months => 6);
while ($date <= $end) {
$csv->say(STDOUT, [$dateparser->format_datetime($date), @$row]);
$date = $date->add(days => 1);
}
}
close $fh;
}
运行它:
perl 6months.pl data.csv
01/01/2017 00:00:00,sampledata,1234,sample,123455,67546464
02/01/2017 00:00:00,sampledata,1234,sample,123455,67546464
...
30/06/2017 00:00:00,sampledata,1234,sample,123455,67546464
01/07/2017 00:00:00,sampledata,1234,sample,123455,67546464
刚刚注意到这会将时间重置为午夜。如果你想节省时间,请这样做:
my $date = $dateparser->parse_datetime($datestr)->set(day => 1);
# ^^^^^^^^^^^^^