How to calculate the difference between two timestamp strings in Perl

Tag: perl Author: whjjk Date: 2013-10-04

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.

what kind of result do you want? number of seconds difference?
is there really a PM? you don't show it in the example.
Hi Ysth , I want the difference to be shown like 12 mins and 5 sec.

Best Answer

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;


12 minutes, 5 seconds


Thank you Borodin for the answer, but it is throwing an error saying Error parsing time at /usr/lib/perl/5.14/Time/ line 469.
@user2457969: Do you get that error with my code as it stands? If you have changed the data then you need to show what changes you have made. As ysth asked, is there a PM on the end? You say there is in your question but it isn't there in your data.
@user2457969: If your date/times actually look like 05/25/2011 05:34:08 PM then you need to use the format %m/%d/%Y %H:%M:%S %p instead.
well your code works fine now, actually I have these lines 'Execution completed at 05/25/2011 05:34:08 PM' and 'Execution started at 05/25/2011 05:22:03 PM', and using this regex ($mon1,$date1,$year1,$hr1,$min1,$sec1) = ($firstline =~ m/(\d+)\/(\d+)\/(\d+) (\d+):(\d+):(\d+)/); I am getting only the numeric values and then appending slash (/) and semicolon and storing them into a string to make it a timestamp. But that is mostly causing the issue, can you tell me what should be the regex used to get only the timestamp value from those lines ? I would really appreciate it. Thanks Borodin.
so I mean what should be the regex to directly get only 05/25/2011 05:22:03 values from the line 'Execution completed at 05/25/2011 05:34:08 PM'.