Perl时间,日期转换错误

时间:2012-05-07 17:14:55

标签: perl date format

这是一个perl脚本,用于从10月1日开始每天提取100天的sql数据 SQL在日期格式(yyyy-mm-dd)中非常挑剔,所以我编写了如下脚本。 但是,在特定日期,在2011-11-06,时间转换不正确,开始和结束日期变得相同。

$srt_date='2011-11-06'
$end_date='2011-11-06'

我不知道这是perl错误还是别的。

use DBI;
use DBD::Oracle qw(:ora_types);
use Compress::Zlib;
use FileHandle;
use Date::Parse;
use Date::Format;

$st_day=str2time('2011-10-1');

@days=(0..100);

foreach $daynum (@days){
$dt1 = $st_day+3600*(24*$daynum);
$dt2 = $st_day+3600*(24*($daynum+1));
$srt_date = time2str("%d-%h-%Y", $dt1);
$end_date = time2str("%d-%h-%Y", $dt2);
print $srt_date, ',' ,$end_date, '\n';
my $sqlGetEid = "select x,y from z where DATETIME>='$srt_date' and DATETIME<'$end_date'";
}

2 个答案:

答案 0 :(得分:1)

以下是DateTime正确处理DST过渡的方式:

use strict; #ALWAYS!
use warnings; #ALWAYS!
use DateTime;

my $st_day = '2011-10-1';

my ($year, $month, $day) = split /-/, $st_day;

my $dt = DateTime->new(
    year => $year,
    month => $month,
    day => $day,
    time_zone => 'local',
);

my @days = 0..100;
foreach my $daynum (@days) {
    my $dt1 = $dt->ymd;
    my $dt2 = $dt->add(days => 1)->ymd;
    printf "%s,%s\n", $dt1, $dt2;
}

答案 1 :(得分:0)

我不确定你想要完全达到什么目的,但是为什么在你可以侥幸逃脱时执行100条SQL语句呢?

SELECT trunc(datetime, 'DD') truncdate, x,y
FROM z WHERE datetime between '2011-10-01'
AND to_date('20111001', 'YYYYMMDD') + 99

使用truncdate作为键填充哈希值,如果您的日期是ISO 8601,则通过使用常规(cmp)排序循环遍历哈希,您将获得相同的排序。

编辑:我将澄清你如何做到这一点:

my $sth = $mdbh->prepare("SELECT trunc(datetime, 'DD') truncdate, x,y
    FROM z WHERE datetime between '2011-10-01'
    AND to_date('20111001', 'YYYYMMDD') + 99
    ORDER BY truncdate");
$sth->execute();

my $lastdate = "";
my $fh;    

while (my $row = $sth->fetchrow_hashref()) {

    # If new date, create new file
    if ($row->{truncdate} ne $lastdate) {
        close($fh) if $fh;
        open($fh, ">", "$row->{truncdate}.csv") or die "Unable to create file '$row->{truncdate}.csv': $!\n";
    }

    print $fh "$row->{x},$row->{y}\n";
    $lastdate = $row->{truncdate};
}
close($fh) if $fh;