Ωmega
Ωmega

Reputation: 43673

Error parsing time-zone with Time::Piece

Executing a simple Perl script

use Time::Piece;
my $t = Time::Piece->strptime('08:00 PM AST', "%I:%M %p %Z");

I got the following error: Error parsing time at /usr/local/lib/perl5/Time/Piece.pm line 469.

Is this a bug in the library or there is something wrong with the above code? When I remove AST time-zone from the input string, it works, but when time-zone is left, it fails.

I don't know what exact time-zone will be in input string, so I cannot adjust that part on my end. AST (see Wikipedia) is a proper abbreviation for Atlantic Time Zone, so it should work. But it does not!

Upvotes: 0

Views: 1760

Answers (2)

Ωmega
Ωmega

Reputation: 43673

use Date::Parse;
my $t = str2time('08:00 PM AST');

Upvotes: -1

Borodin
Borodin

Reputation: 126722

The time zone field is ambiguous and cannot be parsed. For instance, CST is the abbreviation for China Standard Time, Central Standard Time, and Cuba Standard Time.

The module documentation says that the strptime method is from FreeBSD, where the %Z format accepts either the local time zone or GMT and nothing else. This may be true of strptime, but I can confirm only that, where I am located, GMT is acceptable while UTC and AST are not.

The solution I would recommend is to preprocess your time strings, replacing the time zone abbreviation with an unambiguous time zone offset. For instance AST (assuming you meant Atlantic Standard Time and not Arabia Standard Time) would be replaced with -0400, since it is four hours behind UTC. Then you can parse it with a %z format specifier and get the correct result.

Upvotes: 8

Related Questions