Perl: how to pretty-print time duration

Posted by sds on Stack Overflow See other posts from Stack Overflow or by sds
Published on 2012-11-02T16:48:19Z Indexed on 2012/11/02 17:01 UTC
Read the original article Hit count: 281

Filed under:
|
|

How do I pretty print time duration in perl?

The only thing I could come up with so far is

my $interval = 1351521657387 - 1351515910623; # milliseconds
my $duration = DateTime::Duration->new(
    seconds => POSIX::floor($interval/1000) ,
    nanoseconds  => 1000000 * ($interval % 1000),
);
my $df = DateTime::Format::Duration->new(
    pattern => '%Y years, %m months, %e days, ' .
               '%H hours, %M minutes, %S seconds, %N nanoseconds',
    normalize => 1,
);
print $df->format_duration($duration);

which results in

0 years, 00 months, 0 days, 01 hours, 35 minutes, 46 seconds, 764000000 nanoseconds

This is no good for me for the following reasons:

  1. I don't want to see "0 years" (space waste) &c and I don't want to remove "%Y years" from the pattern (what if I do need years next time?)
  2. I know in advance that my precision is only milliseconds, I don't want to see the 6 zeros in the nanoseconds part.
  3. I care about prettiness/compactness/human readability much more than about precision/machine readability. I.e., I want to see something like "1.2 years" or "3.22 months" or "7.88 days" or "5.7 hours" or "75.5 minutes" (or "1.26 hours, whatever looks better to you) or "24.7 seconds" or "133.7 milliseconds" &c (similar to how R prints difftime)

© Stack Overflow or respective owner

Related posts about perl

Related posts about datetime