Reputation: 45
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
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
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