Convert seconds to days, hours, minutes using Perl
Asked Answered
B

2

5

I would like to take control of the output generated in seconds using perl. I would like to show the time (in seconds) in the form of days, hours, minutes and seconds to make it human readable format.

my $start = time;
<some other perl codes>
my $duration = time - $start;
print "Total Execution time: $duration s\n";

Output is 311052 s

Required Output is 3 days 14 hours 24 minutes 12 seconds

Britanybritches answered 14/9, 2015 at 11:50 Comment(4)
Links to name a few: #16020348, #20050165, #7546164, #7546164Britanybritches
What's wrong with the last one you mention?Stallard
@JB - Adding just those modules will help? What changes should I add in those few lines of code?Britanybritches
Going through half of the relevant StackOverflow answers won't help if you don't allow it to.Stallard
C
15

You could use the Time::Piece and Time::Seconds modules, which will do all of this for you

In this program I have simply added pi days onto the current date and time to get a representative duration. You will, of course, use an actual time

use strict;
use warnings;

use Time::Piece;
use Time::Seconds qw/ ONE_DAY /;

my $start = localtime;
my $end = $start + int(355/113 * ONE_DAY);

my $duration = ($end - $start)->pretty;
print "Total Execution time: $duration\n";

output

Total Execution time: 3 days, 3 hours, 23 minutes, 53 seconds
Catalinacatalo answered 14/9, 2015 at 12:20 Comment(4)
Your code worked perfectly. Small issue here, my execution time is random. Sometimes it generates 311052 s sometimes only 17653 s sometimes 24 s.Britanybritches
@arka.b: Why is that a problem?Catalinacatalo
Yes, because my execution time varies. Say my execution ran for 12 hours 14 seconds it will still show me 3 days, 3 hours, 23 minutes, 53 secondsBritanybritches
@arka.b: My second paragraph says "In this program I have simply added pi days onto the current date and time to get a representative duration. You will, of course, use an actual time". You need to call localtime again to get the actual end time. I didn't imagine that all of your execution times were exactly 3.14 days!Catalinacatalo
T
-2

I don't like to use modules for simple things:

sub seconds_to_dhms {
    my $total_seconds = shift;

    # Calculate days
    my $days = int($total_seconds / 86400);
    $total_seconds -= $days * 86400;

    # Calculate hours
    my $hours = int($total_seconds / 3600);
    $total_seconds -= $hours * 3600;

    # Calculate minutes
    my $minutes = int($total_seconds / 60);
    $total_seconds -= $minutes * 60;

    # Remaining is seconds
    my $seconds = $total_seconds;

    # Return formatted string
    return sprintf("%d days, %02d hours, %02d minutes, and %02d seconds", $days, $hours, $minutes, $seconds);
}
Tagmemics answered 29/10 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.