in reply to Convert time in seconds to hh::mm::ss

Update: I saw in one of your replies that you only want hour:min:sec so my suggestion below is probably not what you want.

Meanwhile I also found that an earlier monk has already benchmarked several solutions to this problem.

You could use the core module Time::Seconds:

#!/usr/bin/perl use strict; use warnings; use Time::Seconds; my $t = Time::Seconds->new( 12345678 ); print $t->pretty; __END__
Output:
142 days, 21 hours, 21 minutes, 18 seconds

Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Convert time in seconds to hh::mm::ss
by stevieb (Canon) on Mar 16, 2016 at 02:07 UTC

    It's always preferred to use core modules, but in this case, as opposed to the OP's sub, you'd have to create a new object per conversion (if my brief overview of the module has me understand it correctly):

    use warnings; use strict; use Benchmark qw(cmpthese); use Time::Seconds; my $time = '12345678'; cmpthese(1000000, { sub => "parse_duration('$time')", mod => "time_seconds('$time')", }); sub parse_duration { my $seconds = shift; my $hours = int( $seconds / (60*60) ); my $mins = ( $seconds / 60 ) % 60; my $secs = $seconds % 60; return sprintf("%02d:%02d:%02d", $hours,$mins,$secs); } sub time_seconds { my $seconds = shift; my $t = Time::Seconds->new($seconds); return $t->pretty; }

    Sometimes it's best just to keep it local:

    Rate mod sub mod 17819/s -- -95% sub 373134/s 1994% --

    kudos for the other day on the quoting of the var in my own bench, fwiw ;)

Re^2: Convert time in seconds to hh::mm::ss
by bangor (Monk) on Mar 16, 2016 at 02:02 UTC
    - Hope this helps!

    That link really does help - thank you! Don't know how I didn't find that myself as was searching quite a bit - almost exactly the same title too.