2

I need to parse some time string that comes in a format like ddmmyyyyhhmmssXXX. The XXX part is millisecond. In the below code Im ignoring the millisecond part. It works but I get the error:

garbage at end of string in strptime: 293 at /usr/local/lib64/perl5/Time/Piece.pm line 482.

Whats the proper format that I should use.

$time = '11032014182819802';
$format = '%d%m%Y%H%M%S';
$t = Time::Piece->strptime($time, $format);
Kamrul Khan
  • 3,260
  • 4
  • 32
  • 59
  • What do you want to do with the milliseconds? Just ignore them? Use them to round the seconds field? Or something else? – Borodin Aug 27 '15 at 08:39
  • I calculate difference between two times. Most of the times it is OK if the difference is in seconds. But in special cases I might need difference in millisecond level aswell. – Kamrul Khan Aug 27 '15 at 16:47

3 Answers3

4
Time::Piece->strptime(substr($time, 0, -3), $format);

since Time::Piece does not support milliseconds.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • This is specific to the example, it does not cover cases where milliseconds are not at the end of the string (and asking about those would be considered a duplicate of this question) – Gert van den Berg May 14 '18 at 16:00
1

If you care about the milliseconds and want to preserve them, you'll need to look into using something else (e.g., DateTime::Format::Strptime).

Matt Jacob
  • 6,503
  • 2
  • 24
  • 27
1

You can use DateTime::Format::Strptime if you want to parse milliseconds, then you may try this:

my $Strp = new DateTime::Format::Strptime(
                                pattern     => '%d%m%Y%H%M%S%3N',
                        );

my $date = $Strp->parse_datetime("11032014182819802");
print $date->millisecond ,"\n";
Gert van den Berg
  • 2,448
  • 31
  • 41
Arunesh Singh
  • 3,489
  • 18
  • 26