如何在perl中获得'毫秒'作为时间的一部分?

Jac*_*mes 14 perl

我需要以格式获得时间,"20130808 12:12:12.123""yyyymmdd hour:min:sec.msec".

我试过了

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); 
$year += 1900;
$mon++;
if ($mon<10){$mon="0$mon"} 
if ($mday<10){$mday="0$mday"} 
if ($hour<10){$hour="0$hour"} 
if ($min<10){$min="0$min"} 
if ($sec<10){$sec="0$sec"}  but this doesn't provide the `msec` as a part of time.
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 ?

Sla*_*zic 24

这是一个完整的脚本.如前所述,它Time::HiRes::time用于微秒支持,它也POSIX::strftime用于更容易的格式化.不幸的是strftime无法处理微秒,因此必须手动添加.

use Time::HiRes qw(time);
use POSIX qw(strftime);

my $t = time;
my $date = strftime "%Y%m%d %H:%M:%S", localtime $t;
$date .= sprintf ".%03d", ($t-int($t))*1000; # without rounding

print $date, "\n";
Run Code Online (Sandbox Code Playgroud)

  • 也可以使用这种类似但略有不同的解决方案: `use Time::HiRes qw( gettimeofday );` `use POSIX qw( strftime );` `my ($sec, $usec) = gettimeofday();` `printf( "%s.%03d", strftime( "%Y%m%d %H:%M:%S", 本地时间 $sec ), $usec/1000 );` (2认同)

Pau*_*aul 10

使用Time :: HiRes

简要地看一下,它可以很容易地提供自epoch以来的毫秒,但似乎没有扩展localtime(),因此在完整的日历环境中使用它可能需要一些工作.

这是一个有效的例子:

use strict;
use warnings;

use Time::Format qw/%time/;
use Time::HiRes qw/gettimeofday/;

my $time = gettimeofday; # Returns ssssssssss.uuuuuu in scalar context

print qq|$time{'yyyymmdd hh:mm:ss.mmm', $time}\n|;
Run Code Online (Sandbox Code Playgroud)

  • `my $time = join '.', gettimeofday;` 很容易出错,因为在列表上下文中,返回的毫秒数没有前导零(例如,当时间为 1234567890.000123 时,您正在连接 1234567890.123,这是错误的。您只需要 `$ time = gettimeofday`,在标量上下文中已经返回 '1234567890.000123'。 (2认同)