Jed Tan
Jed Tan

Reputation: 39

Perl Strptime Error

I am currently trying to parse data from a CSV file, which in the first column has time stamps that look like this:

07/26/2014 00:23:09

I read the documentation for Time::Piece which I already use to parse other types of timestamps, and it seems that the format string for this time style should be "%D %T". However, when I try the line

$temp_time = Time::Piece->strptime($fields[0], "%D %T");

Where $fields[0] is the string containing the timestamp, I get this type of warning when executing:

 garbage at end of string in strptime:  03:19:24 at /usr/local/lib64/perl5/Time/Piece.pm line 469, <$data> line 11933.

Any pointers? I've also tried "%m/%y/%d %H:%M:%S" and that does not seem to work.

Thanks!

Upvotes: 0

Views: 2297

Answers (3)

AgileDan
AgileDan

Reputation: 361

I tried your initial way with the following:

use strict;
use warnings;
use Time::Piece;

my $time = Time::Piece->strptime(
    "07/26/2014 00:23:09", 
    "%m/%d/%Y %H:%M:%S");
print $time;

Upvotes: 0

ThisSuitIsBlackNot
ThisSuitIsBlackNot

Reputation: 24063

The %D format specifier is equivalent to %m/%d/%y, where %y (lowercase 'y') is the year without the century (i.e. 0-99). You're using a four-digit year, so that won't work.

Instead, use

my $t = Time::Piece->strptime('07/26/2014 00:23:09', '%m/%d/%Y %T');

(note the uppercase %Y)

Run man strptime for more information about format specifiers, or see the FreeBSD manpage linked from the Time::Piece documentation.

Upvotes: 1

Miller
Miller

Reputation: 35198

Your second format string has the year in the middle spot.

Perhaps the following will help you:

use strict;
use warnings;

use Time::Piece;

my $str = '07/26/2014 03:19:24';

my $t = Time::Piece->strptime($str, "%m/%d/%Y %H:%M:%S");

print $t->strftime("%a, %d %b %Y"), "\n";

Outputs:

Sat, 26 Jul 2014

Upvotes: 0

Related Questions