How to calculate the difference between two lines of a timestamp in Perl

I looked through all the possible questions, but could not find the answer, so can Perl experts help me with this?

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 last is the end time of the assignment, and the first is the start time.

How to find out the difference in dates and time? In this case, the dates are the same, but they may differ.

+6
source share
2 answers

I recommend you use the Time::Piece module. It has been a core module since the release of version 9.5 of Perl 5, so it does not need to be installed.

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 
+10
source

You can use DateTime and the 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"; 
+1
source

Source: https://habr.com/ru/post/956373/


All Articles