如何在Perl中将时间转换为hh:mm:ss格式?

时间:2015-07-22 07:51:20

标签: perl posix strftime

我们需要将数字格式的时间列转换为标准时间格式,即hh:mm:ss in perl。

示例:

  1. 如果时间值为1500,则转换后的值应为00:15:00
  2. 如果时间值为11500,则转换后的值应为01:15:00
  3. 我试过这个:

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

    但输出为00:25:00,我需要输出为00:15:00

    我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

首先需要通过添加左零填充来将数字设置为六位数。之后,您需要在每两位数后插入冒号:。最简单的方法是使用sprintf和正则表达式。

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;

<强>输出

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

请注意,对于长度大于6的字符串,它会中断。

答案 1 :(得分:1)

更新

要将24小时转换为12小时,最好使用Time::Piece模块将%H%M%S转换为%I:%M:%S%p。 {0}仍然需要sprintf作为将字符串填充为零到六位数

的初始步骤

此示例程序每小时从5900到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');
}

输出

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

原始解决方案

在此解决方案中,sprintf('%06d', $time)用于使用零将字符串填充为六位数,/../g将结果拆分为两个字符的(三个)块。 join ':'重新组合中间有冒号的块,以达到所需的模式

my $time = 1500;

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

print $converted, "\n";

输出

00:15:00

答案 2 :(得分:-2)

我找到了这段代码,请尝试

#!/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);

我们的看跌期权: 时间格式 - HH:MM:SS 6点58分52秒