Jyxton Plu
Jyxton Plu

Reputation: 45

How can I display the current datetime in the given format including microseconds in Perl?

I want Perl to display current date and time in the following format:

2010-02-11 13:12:34.87876

I wrote this code:

use Time::localtime;
my $tm = localtime;
printf("It is now %04d-%02d-%02d %02d:%02d:%02d\n", $tm->year+1900,
    ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec);

and got:

2011-11-17 17:22:59

I do not know how to get the remaining .87876 in the output. Could someone please help me?

Upvotes: 3

Views: 1088

Answers (3)

Eugene Yarmash
Eugene Yarmash

Reputation: 149756

Using DateTime and Time::HiRes:

use DateTime;
use Time::HiRes;

my $dt = DateTime->from_epoch(
    epoch     => Time::HiRes::time,
    time_zone => 'local',
);
print $dt->strftime("%Y-%m-%d %H:%M:%S.%5N"); # 2011-11-17 21:03:46.74562

This is exactly how DateTime::HiRes creates DateTime objects with sub-second resolution.

Upvotes: 8

daxim
daxim

Reputation: 39158

use DateTime::HiRes qw();
DateTime::HiRes->now(time_zone => 'local')->strftime('%F %T.%5N')
# returns '2011-11-17 17:42:42.21719'

Upvotes: 11

Samuel Liew
Samuel Liew

Reputation: 79032

You might be looking for %5N. See DateTime::Format

Upvotes: 1

Related Questions