|
Posted by John W. Krahn on May 12, 2008, 2:52 pm
Please log in for more thread options Peter J. Holzer wrote:
>> ambarish.mitra@gmail.com wrote:
>>> I need to get the current date-time with milliseconds upto 5 places of
>>> precision.
>>>
>>> That is, 20080512T12094565266 => YYYY MM DD T HH mm SS ms-5 digits
>>>
>>> Here, 65266 is the milli-second with 5 places of precision.
> [...]
>>> Any idea how this can be achieved in Perl?
>> $ perl -le'
>> use Time::HiRes q/gettimeofday/;
>> use POSIX q/strftime/;
>> print substr strftime( q/%Y%m%dT%H%M%S/, localtime ) . ( gettimeofday )[
>> 1 ] . q/00000/, 0, 20;
>> '
>> 20080512T03134231838
>>
>> Of course there is no guarantee that the microseconds will apply to the
>> seconds field that strftime produces.
>
> That's because you are getting the "current time" twice: Once with
> localtime and once with gettimeofday, and then you use the seconds from
> the first call and the microseconds from the second call. Of course the
> seconds may have changed between the calls. If you get the current time
> only once that cannot happen:
>
> my ($seconds, $microseconds) = gettimeofday;
> print strftime( q/%Y%m%dT%H%M%S/, localtime($seconds)),
> sprintf("%05d", $microseconds/10);
>
> (your code also prints the fractional part wrong: 2713 microseconds
> should be printed as 00271 but is printed as 27130)
Thanks Peter, I didn't know how microseconds were represented.
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
|