Here i based one problem.. i have two timestamps with same format like (Tue Dec 14 18:23:19 2010 & Tue Dec 14 17:23:19 2010). how can i get the difference of two timestamps in hours. please help me
Asked
Active
Viewed 6,216 times
-1
-
2http://stackoverflow.com/questions/821423/how-can-i-calculate-the-number-of-days-between-two-dates-in-perl http://stackoverflow.com/questions/1555101/how-can-i-use-perl-to-do-datetime-comparisons-and-calculate-deltas http://stackoverflow.com/questions/3388958/how-do-i-calculate-a-datetime-difference-in-perl – daxim Dec 16 '10 at 14:48
3 Answers
10
use Date::Parse;
my $t1 = 'Tue Dec 14 17:23:19 2010';
my $t2 = 'Tue Dec 14 18:23:19 2010';
my $s1 = str2time( $t1 );
my $s2 = str2time( $t2 );
print $s2 - $s1, " seconds\n";

Jiří Polcar
- 1,192
- 9
- 15
5
I use the DateTime family of classes for pretty much all of my date/time handling.
#!/usr/bin/perl
use strict;
use warnings;
use DateTime::Format::Strptime;
my $dp = DateTime::Format::Strptime->new(
pattern => '%a %b %d %H:%M:%S %Y'
);
# Create two DateTime objects
my $t1 = $dp->parse_datetime('Tue Dec 14 17:23:19 2010');
my $t2 = $dp->parse_datetime('Tue Dec 14 18:23:19 2010');
# The difference is a DateTime::Duration object
my $diff = $t2 - $t1;
print $diff->hours;

Dave Cross
- 68,119
- 3
- 51
- 97
-
4but its durations have some gotchas for the unwary. Your code does not work if the two timestamps have different days. – ysth Dec 16 '10 at 17:11
1
You can take advantage of DateTime and its subtract_datetime() method, which returns a DateTime::Duration object.
use Date::Parse;
use DateTime;
my $t1 = 'Tue Dec 14 17:23:19 2010';
my $t2 = 'Tue Dec 14 18:23:19 2010';
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 hours: " . $diff->in_units('hours') . "\n";
print "Diff in months: " . $diff->in_units('months') . "\n";

Paolo Rovelli
- 9,396
- 2
- 58
- 37