我希望使用Perl获得以下字符串的时差:
2013-12-27 13:28:14.975952
2013-12-27 13:28:16.345667
(微秒)。 我尝试使用mktime
并从时代开始获得毫秒数,但这并没有多大帮助。
如果我使用Time::HiRes模块,我如何转换上述时间以获得差异?或者你有更好的建议吗?
答案 0 :(得分:1)
use DateTime::Format::Strptime qw( );
my $format = DateTime::Format::Strptime->new(
pattern => '%Y-%m-%d %H:%M:%S',
on_error => 'croak',
time_zone => 'local',
);
sub parse_datetime {
my ($str) = @_;
my $nano;
if ($str =~ /^([^.]*)\.(\d+)\z/) {
$str = $1;
$nano = "0.$2" * 1_000_000_000;
} else {
$nano = 0;
}
return $format->parse_datetime($str)->add( nanoseconds => $nano );
}
sub diff {
return
$_[1]->subtract_datetime_absolute($_[0])
->in_units('nanoseconds')
/ 1_000_000_000
}
my $dt1 = parse_datetime('2013-12-27 13:28:14.975952');
my $dt2 = parse_datetime('2013-12-27 13:28:16.0345667');
my $diff = diff($dt1, $dt2);
print("$diff\n");
但我有点困惑。 Time :: HiRes中的任何内容都返回2013-12-27 13:28:14.975952
之类的内容。如果您实际使用Time::HiRes::time
,则可以使用以下内容:
use DateTime qw( );
sub diff {
return
$_[1]->subtract_datetime_absolute($_[0])
->in_units('nanoseconds')
/ 1_000_000_000
}
my $dt1 = DateTime->from_epoch( epoch => 1388461836.975952, time_zone => 'local' );
my $dt2 = DateTime->from_epoch( epoch => 1388461838.0345667, time_zone => 'local' );
my $diff = diff($dt1, $dt2);
print("$diff\n");
答案 1 :(得分:1)
如果不能选择DateTime和DateTime::Format::Strptime,则自{5.1}以来Time::Piece一直处于核心状态。
use Time::Piece;
sub str2time {
my ($str) = @_;
$str =~ s/(\.[0-9]+)?\z//;
my $fraction = $1 || 0;
return Time::Piece->strptime($str, '%Y-%m-%d %H:%M:%S')->epoch + $fraction;
}
my $t1 = str2time('2013-12-27 13:28:14.975952');
my $t2 = str2time('2013-12-27 13:28:16.345667');
printf "difference: %f\n", $t2 - $t1;