Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

time - Perl calculate difference between 2 timestamps

I have 2 variables with the following time stamp and would like to get the difference between them

 my $startdate = "2015/01/13 13:57:02.079-05:00";
 my $enddate ="2015/01/13 13:59:02.079-05:00";

How can I achieve the time difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using DateTime, it's simply

$edt->subtract_datetime_absolute($sdt)->in_units('nanoseconds') / 1e9

All that's left is generating the DateTime objects. For that, DateTime::Format::Strptime is almost perfect.

use DateTime::Format::Strptime qw( );

my $sts = "2015/01/13 13:57:02.079-05:00";
my $ets = "2015/01/13 13:59:02.079-05:00";

my $format = DateTime::Format::Strptime->new(
   pattern  => '%Y/%m/%d %H:%M:%S.%3N%z',
   on_error => 'croak',
);

my $sdt = $format->parse_datetime( $sts =~ s/:(?=ddz)//r );
my $edt = $format->parse_datetime( $ets =~ s/:(?=ddz)//r );

my $diff = $edt->subtract_datetime_absolute($sdt)->in_units('nanoseconds') / 1e9;
printf("%.3f
", $diff);  # 120.000

If you want the code to also run on Perl versions older than 5.14, replace

my $sdt = $format->parse_datetime( $sts =~ s/:(?=ddz)//r );
my $edt = $format->parse_datetime( $ets =~ s/:(?=ddz)//r );

with

s/:(?=ddz)// for $sts, $ets;

my $sdt = $format->parse_datetime($sts);
my $edt = $format->parse_datetime($ets);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...