perl:计算时间戳之间的持续时间

时间:2016-10-14 18:38:44

标签: perl

我有一系列字符串对

$str1 = '2016-09-29 10:02:29';
$str2 = '2016-09-29 10:05:45';

第一个字符串总是在第二个字符串之前 我想说服两个时间戳之间经过了多少秒

以上将是196秒

有一种快速计算两个时间戳之间差异的方法吗?

(已废弃)更新:我编写了以下代码,我收到此错误

my $format = DateTime::Format::Strptime->new(
   format    => '%Y-%m-%d %H:%M:%S',
   time_zone => 'UTC',
   on_error  => 'croak',
);

The following parameter was passed in the call to DateTime::Format::Strptime::new but was not listed in the validation options: format
 at /usr/software/lib/perl5/site_perl/5.8.8/DateTime/Format/Strptime.pm line 130.
    DateTime::Format::Strptime::new(undef, 'format', '%Y-%m-%d %H:%M:%S', 'time_zone', 'UTC', 'on_error', 'croak') called at ./show_startup.pl line 150

2 个答案:

答案 0 :(得分:5)

使用DateTime(和DateTime::Format::Strptime):

use DateTime::Format::Strptime qw( );

my $str1 = '2016-09-29 10:02:29';
my $str2 = '2016-09-29 10:05:45';

my $format = DateTime::Format::Strptime->new(
   pattern   => '%Y-%m-%d %H:%M:%S',
   time_zone => 'local',  # If they are local time timestamps
      -or-
   time_zone => 'UTC',    # If they are UTC timestamps
   on_error  => 'croak',
);

my $dt1 = $format->parse_datetime($str1);
my $dt2 = $format->parse_datetime($str2);

my $seconds = $dt2->delta_ms($dt1)->in_units('seconds');

使用Time::Piece

use Time::Piece qw( localtime );

my $str1 = '2016-09-29 10:02:29';
my $str2 = '2016-09-29 10:05:45';

my $format = '%Y-%m-%d %H:%M:%S';

my $t1 = Time::Piece->strptime($str1, $format);  # If they are UTC timestamps
my $t2 = Time::Piece->strptime($str2, $format);  # 
  -or-
my $t1 = localtime->strptime($str1, $format);    # If they are local time timestamps
my $t2 = localtime->strptime($str2, $format);    #

my $seconds = ($t2 - $t1)->seconds;

答案 1 :(得分:0)

这是一种方法,使用Perl附带的Time::Piece模块:

use strict;
use warnings;

use Time::Piece;

my $str1 = '2016-09-29 10:02:29';
my $str2 = '2016-09-29 10:05:45';

my $format = '%Y-%m-%d %H:%M:%S';
my $t1 = Time::Piece->strptime($str1, $format);
my $t2 = Time::Piece->strptime($str2, $format);

my $seconds = ($t2 - $t1)->seconds;
print "Result: $seconds\n";

此代码不考虑本地时区,即假定时间以UTC为单位。