Search code examples
perlposixstrftime

How can I convert a time to hh:mm:ss format in Perl?


We need to convert the time column which is in number format to standard time format ie hh:mm:ss in perl.

Example:

  1. If the time value is 1500, the converted value should be 00:15:00.
  2. If the time value is 11500, the converted value should be 01:15:00.

I have tried this:

use POSIX qw(strftime); 
printf( strftime("%H:%M:%S",localtime(1500))); 

But the output is 00:25:00 and I need the output to be 00:15:00.

How can I solve this?


Solution

  • Update

    To also convert from 24-hour to 12-hour time, it is probably best to use the Time::Piece module to convert from %H%M%S to %I:%M:%S%p. sprintf is still necessary as an initial step to pad the string with zeroes to six digits

    This example program formats and prints time values each hour from 5900 to 235900

    use strict;
    use warnings;
    use 5.010;
    
    use Time::Piece;
    
    say format_time(1500);
    say format_time(11500);
    say '';
    
    for my $time (0 .. 23) {
        $time = $time * 10000 + 5900;
        say format_time($time);
    }
    
    sub format_time {
        my ($time) = @_;
        $time = Time::Piece->strptime(sprintf('%06d', $time), '%H%M%S');
        lc $time->strftime('%I:%M:%S%p');
    }
    

    output

    12:15:00am
    01:15:00am
    
    12:59:00am
    01:59:00am
    02:59:00am
    03:59:00am
    04:59:00am
    05:59:00am
    06:59:00am
    07:59:00am
    08:59:00am
    09:59:00am
    10:59:00am
    11:59:00am
    12:59:00pm
    01:59:00pm
    02:59:00pm
    03:59:00pm
    04:59:00pm
    05:59:00pm
    06:59:00pm
    07:59:00pm
    08:59:00pm
    09:59:00pm
    10:59:00pm
    11:59:00pm
    

    Original solution

    In this solution, sprintf('%06d', $time) is used to pad the string to six digits using zeroes, and /../g splits the result into (three) chunks of two characters. The join ':' reassembles those chunks with colons in between to achieve the desired pattern

    my $time = 1500;
    
    my $converted = join ':', sprintf('%06d', $time) =~ /../g;
    
    print $converted, "\n";
    

    output

    00:15:00