Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display the current date and time, including microseconds?

Tags:

datetime

perl

I need to display the date in the following format in one of my programs:

day - month - year "HH:MM:SS". <microseconds>

I am using Perl 5.8 and I have tried using epoch seconds and converting the time to microseconds like this:

my $epoch = time();
my $time1 = ($epoch - int($epoch)) *1e6

But I am getting this output:

25-05-2016 18:20:20.<incorrect number>
like image 326
ruby Avatar asked Oct 25 '25 15:10

ruby


2 Answers

Use Time::HiRes

Example:

#!/usr/bin/env perl                                                                             

use strict;
use warnings;

use Time::HiRes qw( time );
use DateTime;

for (1..3) {
    my $dt = DateTime->from_epoch( epoch => time() );
    print $dt->strftime("%d-%m-%Y %H:%M:%S.%6N") . "\n";
    sleep 1;
}

Output:

25-05-2016 17:42:16.411722
25-05-2016 17:42:17.414295
25-05-2016 17:42:18.415920
like image 198
xxfelixxx Avatar answered Oct 27 '25 11:10

xxfelixxx


To get what you want,

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

my $epoch = time();
my $microsecs = ($epoch - int($epoch)) *1e6;

say strftime("%d-%m-%Y %H:%M:%S", localtime($epoch)) . "." . sprintf("%06.0f", $microsecs);

Output:

25-05-2016 10:50:01.088676

sprintf is used to pad and round to the nearest microsecond.


Alternative:

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

my ($epoch, $microsecs) = gettimeofday();

say strftime("%d-%m-%Y %H:%M:%S", localtime($epoch)) . "." . sprintf("%06d", $microsecs);
like image 45
ikegami Avatar answered Oct 27 '25 11:10

ikegami