【问题标题】:Time interval between two dates with PerlPerl 两个日期之间的时间间隔
【发布时间】:2022-01-22 07:34:30
【问题描述】:

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

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;

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

【问题讨论】:

  • 提示:所有our 都是错误的,应该是myour 用于需要在包外看到的变量。基本上,在使用 Exporter 时将 our 用于 @EXPORT_OK 和类似的,就是这样。
  • 使用 Perl 5.30,您不需要安装 Time::Piece,它应该是 Perl 本身的一部分(除非您使用的发行版破坏了 Perl 包)。
  • 总是使用use strict; use warnings;!这会为您的代码列出一长串问题。
  • @ikegami... 我使用严格和警告,但没有收到有关 Time::Piece 的消息。
  • 呃,你的代码甚至不能用use strict; use warnings; 编译。你是在嘲笑你只是忽略了它吐出的大量警告吗?

标签: perl datetime


【解决方案1】:

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

问题:

  • 没有第 20 个月

  • 没有上午 13 点

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

另外,strptime 忽略了几个问题:

  • 您应该在 12 小时内使用 %I 而不是 %H

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


您似乎在问以下问题:

给定本地时间的年、月、日、时、分和秒组成部分,我如何获得对应的纪元时间以便进行差值处理?

要实现这一点,请使用Time::Localtimelocal*

use Time::Local qw( timelocal_posix );

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

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

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

【讨论】:

    【解决方案2】:

    我使用脚本:

    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;
    

    成功了。

    非常感谢池上的帮助。

    【讨论】:

    • 啊,这就是你想要达到的目标?请参阅我的更新答案。
    猜你喜欢
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    相关资源
    最近更新 更多