Search code examples
perlstrftimestrptime

Perl strptime format differs from strftime


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?


Solution

  • 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.