我在解析 MySQL 结果中的日期时遇到问题。我确信这与多级哈希中的值有关,但我不确定需要在哪里改变元素才能获得所需的效果
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
use Data::Dumper;
use DBI;
use DateTime::Format::MySQL;
use DateTime::Format::DateParse;
our $now = DateTime->now(time_zone=>'America/New_York');
my $dbh = DBI->connect('DBI:mysql:database=cacti;host=localhost;port=3306', 'user', 'password');
my $sth = $dbh->prepare('
SELECT hostname, description, notes, status, disabled, status_rec_date
FROM host;
');
$sth->execute();
my $ref = $sth->fetchall_hashref('hostname');
$sth->finish;
$dbh->disconnect();
print Dumper verify($ref->{$_}) for (keys %{$ref});
sub verify {
my $node = shift;
my $date = $node->{'status_rec_date'};
#my $date = '2017-06-25 00:55:00';
$node->{elapsed} = DateTime::Format::DateParse->parse_datetime($date);
return $node->{elapsed};
}
日期以2017-06-25 00:55:00
的格式存储在数据库中,与DateTime::Format::MySQL
中的输入示例一致code> (除了 DateTime::Format::DateParse
之外,我也尝试过)。
如果我手动将 $date
设置为 2017-06-25 00:55:00
那么一切都会按预期工作,但是当我以以下形式传递该字符串时哈希元素,或将该哈希元素分配给变量,脚本将失败。
使用 hashref 时出错:
$ ./hosts.pl
Validation failed for type named DayOfMonth declared in package DateTime::Types (/usr/local/lib64/perl5/DateTime/Types.pm) at line 29 in sub named (eval) with value 00
Trace begun at Specio::Exception->new line 57
Specio::Exception::throw('Specio::Exception', 'message', 'Validation failed for type named DayOfMonth declared in package DateTime::Types (/usr/local/lib64/perl5/DateTime/Types.pm) at line 29 in sub named (eval) with value 00', 'type', 'Specio::Constraint::Simple=HASH(0x3925e08)', 'value', 00) called at (eval 256) line 85
DateTime::_check_new_params('hour', 00, 'minute', 00, 'month', 0, 'second', 0, 'day', 00, 'year', 1900, 'time_zone', -0400) called at /usr/local/lib64/perl5/DateTime.pm line 165
DateTime::new('DateTime', 'hour', 00, 'minute', 00, 'month', 0, 'second', 0, 'day', 00, 'year', 1900, 'time_zone', -0400) called at /usr/local/share/perl5/DateTime/Format/DateParse.pm line 75
DateTime::Format::DateParse::parse_datetime('DateTime::Format::DateParse', '0000-00-00 00:00:00') called at hosts.pl line 43
最佳答案
明显的调试步骤是在 verify()
子例程中打印 $node->{'status_rec_date'}
的值。我怀疑您会发现数据并不是您想象的那样。
查看错误消息中的堆栈跟踪,外部调用是:
DateTime::Format::DateParse::parse_datetime('DateTime::Format::DateParse', '0000-00-00 00:00:00') called at hosts.pl line 43
您正在传递“0000-00-00 00:00:00”。这不是有效的日期字符串。
看来问题出在您的数据库中。我会注意到,您获得的字符串是一个无效日期,当它没有有效值时,MySQL 似乎喜欢将其插入到日期时间字段中 - 因此您可能需要查看该字段是如何填充的。
关于mysql - 从 MySQL 数据库解析 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45016693/