Home > Back-end >  Time::Piece strptime has trouble with %X
Time::Piece strptime has trouble with %X

Time:02-23

I'm trying to parse the following data using Time::Piece->strptime() in perl v5.26:

my $str = "Mon Feb 21 02:54:49 IST 2022";
my $time_zone = substr($str, 20, 3);
my $date_time = Time::Piece->strptime($str, "%a %b %e %X $time_zone %Y");
print "Todays date/time is : $date_time";

But, when I execute the above code snippet, I get the following error:

Error parsing time at /usr/local/lib64/perl5/Time/Piece.pm line 598.

I'm not sure what is it that I'm missing out, any help will be really helpful.

CodePudding user response:

%X without the final AM/PM only works at the end of a string.

my $str = "Mon Feb 21 IST 2022 02:54:49";
my $time_zone = substr($str, 11, 3);
warn $time_zone;
my $date_time = Time::Piece->strptime($str, "%a %b %e $time_zone %Y %X");
print "Todays date/time is : $date_time";

or

my $str = "Mon Feb 21 02:54:49 AM IST 2022";
my $time_zone = substr($str, 23, 3);
my $date_time = Time::Piece->strptime($str, "%a %b %e %X $time_zone %Y");
print "Todays date/time is : $date_time";

But my testing shows this behaviour is Perl version dependent, so maybe don't use %X (same as %I:%M:%S %p) at all and switch to %T (same as %H:%M:%S).

my $str = "Mon Feb 21 02:54:49 IST 2022";
my $time_zone = substr($str, 20, 3);
my $date_time = Time::Piece->strptime($str, "%a %b %e %T $time_zone %Y");
print "Todays date/time is : $date_time";
  • Related