Perl 两个日期之间的时间间隔

Time interval between two dates with Perl

我正在添加两个日期并尝试计算时间,但出现以下错误:

Error parsing time at /usr/local/lib/x86_64-linux-gnu/perl/5.30.0/Time/Piece.pm line 598.

我用 cpan 安装 Time::Piece: cpan Time::Piece.

这是我的代码:

our @months = qw( 01 02 03 04 05 06 07 08 09 10 11 12 );
our @days = qw(Domingo Segunda Treça Quarta Quinta Sexta Sabado Domingo);

 ($sec,$min,$hour,$mday,$mon,$year,$wday,$day,$isdst) = localtime();
 our $ano = "2021";
 our $day = "$mday";
 our $mes = $months[$mon];
 our $data = $mes."-".$day."-".$ano; 
 our $horario = $hour.":".$min.":".$sec;
 our $horario2 = $hour.":".$min.":".$sec;
 our $data1 = $ano."-".$mes."-".$day;
 our $data2 = $day."/".$mes."/".$ano;
 our $str1 = 'Execution completed at '.$data2.' '.$horario.' AM';

 our @mes = qw( Jan Feb Mar APr May Jun Jul Agu Sep Oct Nov Dec );
 our @days = qw(Domingo Segunda Treça Quarta Quinta Sexta Sabado Domingo);

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

$nomeMes = $mes[$mon];

our @mes = qw( Jan Feb Mar APr May Jun Jul Agu Sep Oct Nov Dec );
our @days = qw(Domingo Segunda Treça Quarta Quinta Sexta Sabado Domingo);

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

our $data2 = $day."/".$mes."/".$ano; 
our $horario = $hour.":".$min.":".$sec;

my $str2 = 'Execution completed at '.$data2.' '.$horario.' AM';
my @times = map Time::Piece->strptime(/(\d.+M)/, '%m/%d/%Y %H:%M:%S %p'), $str1, $str2;

my $delta = $times[1] - $times[0];

$tempo = $delta->pretty;

我做错了什么?我该怎么做才能使这个功能发挥作用?

$str1的匹配模式是20/12/2021 13:58:3 AM

问题:

  • 没有第20个月

  • 没有中午13点

  • 在夏令时切换附近可能会给出错误答案。

此外,还有一些问题 strptime 忽略了:

  • 您应该使用 %I 而不是 %H 的 12 小时时间。

  • 通常预期的位置(分钟和秒)缺少前导零。


您似乎在问以下问题:

Given the year, month, day, hour, minute and second components of a local time, how do I obtain the corresponding epoch time so I can perform a difference?

为此,请使用 Time::Localtimelocal*

use Time::Local qw( timelocal_posix );

my $time = timelocal_posix( $sec, $min, $hour, $day, $month - 1, $year - 1900 );

您也可以使用 DateTime。这个更强大的模块可以为您提供秒数以外的数量差异。

无论哪种方式,您在从 DST 切换时仍然会遇到问题。根本没有足够的信息来解决这个问题。这就是在没有偏移量的情况下处理当地时间的问题。

我使用脚本:

our $str2 = $ano.'/'.$mes.'/'.$day.' '.$hour.':'.$min.':'.$sec.'.267-05:00';

my @times = map Time::Piece->strptime( s/\..*//r, '%Y/%m/%d %H:%M:%S'), $str1, $str2; 
our $delta = $times[1] - $times[0];
print $delta->pretty;

工作顺利。

非常感谢池上的帮助。