2

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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592

1 Answers1

3

%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";
choroba
  • 231,213
  • 25
  • 204
  • 289
  • I end up making the code work with ```my $date = Time::Piece->strptime($str, "%a %b %d %T %Y");``` But. If I add $time_zone, like ```my $date = Time::Piece->strptime($str, "%a %b %d %T $time_zone %Y");``` it wont print the timezone.. Anything that we can do for it? – Harsh Gupta Feb 21 '22 at 11:29
  • If you have a different question, ask a new question. You can link to the old one for context. – choroba Feb 22 '22 at 08:58