Bastian
Bastian

Reputation: 129

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?

Upvotes: 1

Views: 2421

Answers (3)

Borodin
Borodin

Reputation: 126722

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

Upvotes: 2

Lasantha
Lasantha

Reputation: 268

I found this code, please try

#!/usr/local/bin/perl

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

printf("Time Format - HH:MM:SS\n");
printf("%02d:%02d:%02d", $hour, $min, $sec);

Our Put : Time Format - HH:MM:SS 06:58:52

Upvotes: -2

simbabque
simbabque

Reputation: 54323

You first need to get the number to six digits by adding left zero padding. After that, you need to insert colons : after every two digits. The easiest way to do that is using sprintf and a regular expression.

use strict;
use warnings;
use feature 'say';

my $date = '11500';
my $formatted = sprintf '%06d', $date;
$formatted =~ s/(\d\d)(\d\d)(\d\d)/$1:$2:$3/;

say $formatted;

Output

01:15:00
00:15:00 (for 1150)

Note it will break for strings with length larger than six.

Upvotes: 4

Related Questions