Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the difference between two timestamp strings in Perl

Tags:

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.

like image 686
skyrocker Avatar asked Oct 20 '13 22:10

skyrocker


People also ask

How do you find the difference in time between two timestamps?

The difference is calculated by subtracting the second operand from the first. The result is rounded down, with any remainder discarded. For example, 61 minutes is equal to 1 hour, and 59 minutes is equal to 0 hours.

How do I get time difference in Perl?

$Diff."\n"; This is a simple way to find the time difference in seconds.

How do I get the difference between two timestamps in PostgreSQL?

To calculate the difference between the timestamps in PostgreSQL, simply subtract the start timestamp from the end timestamp. Here, it would be arrival - departure . The difference will be of the type interval , which means you'll see it in days, hours, minutes, and seconds.


2 Answers

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
like image 87
Borodin Avatar answered Sep 18 '22 01:09

Borodin


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";
like image 20
Paolo Rovelli Avatar answered Sep 20 '22 01:09

Paolo Rovelli