Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 'milliseconds' as a part of time in perl? [duplicate]

Tags:

perl

I need to get the time in the format "20130808 12:12:12.123" i.e., "yyyymmdd hour:min:sec.msec".

I tried

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.

How can i do that ?

like image 525
Jackie James Avatar asked Aug 07 '13 09:08

Jackie James


People also ask

How do I get milliseconds Perl?

In Perl if you want to calculate time in milliseconds (thousandths of a second) you can use Time::HiRes and the time() function.

What is Strftime in Perl?

You can use the POSIX function strftime() in Perl to format the date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent. Specifier. Replaced by. Example.

How do I print a timestamp in Perl script?

Timestamp can be created by creating a DateTime object and then calling the now constructor. my $datetime = DateTime->now; print "$datetime\n" ; A DateTime object can also be created by providing all the details part wise like date, hour, minute, second, etc.


2 Answers

Here's a complete script. As proposed before, it is using Time::HiRes::time for microsecond support, and it's also using POSIX::strftime for easier formatting. Unfortunately strftime cannot deal with microseconds, so this has to be added manually.

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";

If you don't mind to use a CPAN module, then I would propose the excellent Time::Moment module:

use Time::Moment;
print Time::Moment->now->strftime("%Y%m%d %T%3f"), "\n";

And if it may be formatted as an ISO8601 date including a time zone offset and microseconds instead of milliseconds, then it's simply:

print Time::Moment->now->to_string, "\n";
like image 159
Slaven Rezic Avatar answered Oct 17 '22 15:10

Slaven Rezic


use Time::HiRes

Looking at this briefly, it can provide milliseconds since epoch fairly easily but didn't seem to extend localtime(), so there's probably a bit of work involved in using it in a full calendar context.

Here's a working example:

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|;
like image 12
Paul Avatar answered Oct 17 '22 15:10

Paul