Dominique
Dominique

Reputation: 17575

Why does strptime from Time::Piece not parse my format?

My collegue (who has left the company) has written a bunch of scripts, including batch and Perl scripts, and I'm getting rid of the regional settings dependencies.

In the last Perl script, he's written the following piece of code:

my $format = "%d.%m.%Y %H:%M";
my $today_converted = Time::Piece->strptime($today, $format) - ONE_HOUR - ONE_HOUR - ONE_HOUR - ONE_HOUR - ONE_HOUR; 

(the idea is to get five hours before midnight of that particular date)

The value of $today seems to be "03/04/2017" (which stands for the third of April (European dateformat)), which seems not to be understood by Time::Piece implementation:

Error parsing time at C:/Perl64/lib/Time/Piece.pm line 481.

Which format can I use which is understood by Time::Piece Perl implementation?

Upvotes: 1

Views: 774

Answers (2)

Dave Cross
Dave Cross

Reputation: 69314

I think it's worth clarifying that strptime() will parse most date and time formats - that's the point of the method. But you need to define the format of the date string that you are parsing. That's what the second parameter to strptime() (in this case, your $format variable) is for.

The letters used in the format are taken from a standard list of definitions which used by every implementation of strptime() (and its inverse, strftime()). See man strptime on your system for a complete list of the available options.

In your case, the format is %d.%m.%Y %H:%M - which means that it will parse timestamps which have the day, month and year separated by dots, followed by a space and the hours and minutes separated by a colon. If you want to parse timestamps in a different format, then you will need to change the definition of $format.

Upvotes: 1

simbabque
simbabque

Reputation: 54381

In the format you have dots . as the date delimiter, but in the data you have slashes /. That's why it doesn't parse. It needs an exact match.

Upvotes: 4

Related Questions