Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Finding the difference between two dates including milliseconds

by 1nickt (Canon)
on Jan 09, 2017 at 13:51 UTC ( [id://1179214]=note: print w/replies, xml ) Need Help??


in reply to Finding the difference between two dates including milliseconds

Hi Anonymous Monk,

You can use DateTime and friends to do this, comparing with subtract_datetime_absolute(), but you'll have to start with a delta in nanoseconds. The code below shows the difference in milliseconds as specified, including fractions.

use strict; use warnings; use feature 'say'; use DateTime::Format::Strptime; my $parser = DateTime::Format::Strptime->new( pattern => '%F %T.%6N', on_error => 'croak', ); while ( <DATA> ) { chomp; my ( $t2, $t1 ) = split /, /; my $dt2 = $parser->parse_datetime( $t2 ); my $dt1 = $parser->parse_datetime( $t1 ); my $delta = $dt2->subtract_datetime_absolute( $dt1 ); my $delta_ms = sprintf( '%.3f', $delta->in_units('nanoseconds') / 1_000_000, ); say for ( $t2, $t1, "Differs by $delta_ms ms", '' ); } __DATA__ 2017-01-09 05:08:04.575804, 2017-01-09 05:08:04.319338 2017-01-09 05:08:17.093719, 2017-01-09 05:08:16.840292 2017-01-09 05:12:48.629407, 2017-01-09 05:12:48.372687 2017-01-09 05:13:25.315665, 2017-01-09 05:13:25.061834 2017-01-09 05:14:08.171994, 2017-01-09 05:14:07.916187 2017-01-09 05:17:03.182747, 2017-01-09 05:17:02.929309 2017-01-09 05:18:46.561289, 2017-01-09 05:18:46.305743 2017-01-09 05:19:09.772227, 2017-01-09 05:19:09.518975
Output:
perl 1179200.pl 2017-01-09 05:08:04.575804 2017-01-09 05:08:04.319338 Differs by 256.466 ms 2017-01-09 05:08:17.093719 2017-01-09 05:08:16.840292 Differs by 253.427 ms 2017-01-09 05:12:48.629407 2017-01-09 05:12:48.372687 Differs by 256.720 ms 2017-01-09 05:13:25.315665 2017-01-09 05:13:25.061834 Differs by 253.831 ms 2017-01-09 05:14:08.171994 2017-01-09 05:14:07.916187 Differs by 255.807 ms 2017-01-09 05:17:03.182747 2017-01-09 05:17:02.929309 Differs by 253.438 ms 2017-01-09 05:18:46.561289 2017-01-09 05:18:46.305743 Differs by 255.546 ms 2017-01-09 05:19:09.772227 2017-01-09 05:19:09.518975 Differs by 253.252 ms

Hope this helps!


The way forward always starts with a minimal test.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1179214]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-04-19 03:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found