ealeon ealeon - 1 year ago 68
Perl Question

perl: calculating duration between timestamps

I have a series of string pairs

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

the first string is always before the second
I would like to calucate how much seconds have passed between the two timestamps

the above would be 196 seconds

is there a quick way to calculate the difference between two timestamps?

(obsolete) Update: I wrote the following code and i m getting this error

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

Answer Source

Using DateTime (and 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
   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');

Using 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);  # 
my $t1 = localtime->strptime($str1, $format);    # If they are local time timestamps
my $t2 = localtime->strptime($str2, $format);    #

my $seconds = ($t2 - $t1)->seconds;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download