3

I'm trying to work with date strings formatted as:

YYYY-MM-DDThh:mm:ss

strftime format for generating this string is %FT%T:

perl -MPOSIX=strftime -E 'say strftime q{%FT%T}, localtime;'

But when I try to parse this date string with Time::Piece:

perl -MPOSIX=strftime -MTime::Piece -E '
  say strftime q{%FT%T}, localtime;
  Time::Piece->strptime( strftime(q{%FT%T}, localtime), q{%FT%T});
'

I got this error:

2013-11-15T17:32:58
Error parsing time at /usr/local/lib/perl/5.14.2/Time/Piece.pm line 469.

Or if I try this:

perl -MPOSIX=strftime -MTime::Piece -E 'Time::Piece->strptime(strftime(q{%F}, localtime), q{%F});'

I got this:

garbage at end of string in strptime: 2013-11-15 at /usr/local/lib/perl/5.14.2/Time/Piece.pm line 469.

In man said %F is ISO8601 date format in strptime and strftime both. Is strptime backward compatible with strftime?

Suic
  • 2,441
  • 1
  • 17
  • 30

2 Answers2

6

The module uses its own implementation of strptime which doesn't understand %F. It doesn't implement its own strftime. It's a disaster waiting to happen - you should definitely use a strftime and strptime that come from the same source. Time::Piece::strptime looks like a desparation move from an era without a widely available, standardized strptime.

Now that strptime is in POSIX, I would expect POSIX.pm to export it so you can use your system's strptime. But apparently that module is also failing to keep up. There is a separate POSIX::strptime module which gives you your C library's strptime without interference. I suggest using that.

5

No, Time::Piece strftime/strptime formats are not always compatible. Use the longer version of the format:

my $str = '2003-03-24T13:32:44';
my $f = '%Y-%m-%dT%H:%M:%S';
my $t = Time::Piece->strptime($str, $f);

print "$t\n";
runrig
  • 6,486
  • 2
  • 27
  • 44