Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string date to Perl DateTime

Tags:

datetime

perl

I'm a newbie in Perl, so please be patient with me:

I am writing a log parser and have successfully parsed "Dec 1 17:45:36.185" into it's individual units (month, day, hour, minute, seconds, milliseconds). I want to convert this to Perl's DateTime object.

I'm having trouble with the milliseconds portion: .185.

I hope to use DateTime::Format::Strptime like such:

my $strp = DateTime::Format::Strptime(
    pattern    => "%b %d %H:%M:%S"    # how do I add the milliseconds part?
)
like image 938
Mark Avatar asked Dec 03 '13 05:12

Mark


2 Answers

If you want to display milliseconds, use this format %3N:

my $strp = DateTime::Format::Strptime(
    pattern    => "%b %d %H:%M:%S.%3N"    # now we have the milliseconds part
)

The number jut before the N means the number of digits that will be displayed.
The number displayed is truncated, not rounded.

like image 87
Toto Avatar answered Nov 18 '22 02:11

Toto


I might be missunderstanding you. But if you want to have an object of this: http://metacpan.org/pod/DateTime and know the individual numbers, why not use the constructor like so:

  use DateTime;

$dt = DateTime->new(
  year       => 1964,
  month      => 10,
  day        => 16,
  hour       => 16,
  minute     => 12,
  second     => 47,
  nanosecond => 500000000,
  time_zone  => 'Asia/Taipei',
);

Or do you wonder how to format that information into a string later? In that case, you could just use sprintf and DateTimes get methods to produce any format you want.

edit: I think i understood you now. DataTime does not have ms, only ns. When constructing, that is no problem, as you can just put nanosecond => ($ms*1000000) but i see how that can be a problem when using ::Strptime. I cannot install DateTime here to test it, but the CPAN does say

%N

Nanoseconds. For other sub-second values use %[number]N.

So when you have a DateTime object with nanoseconds, you could play with that [number] value to see what it does and when you have found a way to tell it that you like ms, it should even work for parsing.

like image 20
DeVadder Avatar answered Nov 18 '22 02:11

DeVadder