skyrocker
skyrocker

Reputation: 199

How to calculate the difference between two timestamp strings in Perl

I searched through all the possible questions but couldn't find the answer, so can Perl experts help me on this one?

I have two timestamps like 05/25/2011 05:22:03 PM and 05/25/2011 05:34:08 PM. They are stored in string form.

my $str1 = '05/25/2011 05:22:03';
my $str2 = '05/25/2011 05:34:08';

The latter being the time of a job ending and former being the time it started.

How do I find out the difference in dates and time? The dates are the same in this case but they could differ as well.

Upvotes: 6

Views: 13065

Answers (2)

Paolo Rovelli
Paolo Rovelli

Reputation: 9684

You can take advantage of DateTime and its subtract_datetime() method, which returns a DateTime::Duration object.

use Date::Parse;
use DateTime;

my $t1 = '05/25/2011 05:22:03';
my $t2 = '05/25/2011 05:34:08';

my $t1DateTime = DateTime->from_epoch( epoch => str2time( $t1 ) );
my $t2DateTime = DateTime->from_epoch( epoch => str2time( $t2 ) );

my $diff = $t2DateTime->subtract_datetime( $t1DateTime );

print "Diff in minutes: " . $diff->in_units('minutes') . "\n";
print "Diff in hours: " . $diff->in_units('hours') . "\n";
print "Diff in months: " . $diff->in_units('months') . "\n";

Upvotes: 3

Borodin
Borodin

Reputation: 126722

I recommend that you use the Time::Piece module. It has been a core module since the release of version 9.5 of Perl 5, so it shouldn't need installing.

This code demonstrates

use strict;
use warnings;

use Time::Piece;

my $str1 = 'Execution started at 05/25/2011 05:22:03 PM';
my $str2 = 'Execution completed at 05/25/2011 05:34:08 PM';

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

my $delta = $times[1] - $times[0];
print $delta->pretty;

output

12 minutes, 5 seconds

Upvotes: 11

Related Questions