strptime format string nasty default

MRAB python at mrabarnett.plus.com
Wed May 9 16:39:33 EDT 2012


On 09/05/2012 20:38, Javier Novoa C. wrote:
> Hi,
>
> I am using time.strptime method as follows:
>
> I receive an input string, representing some date in the following
> format:
>
> %d%m%Y
>
> However, the day part may be a single digit or two, depending on
> magnitude.
>
> For example:
>
> '10052012' will be parsed as day 10, month 5, year 2012
>
> Again:
>
> '8052012' will be parsed as day 8, month 5, year 2012
>
> What happens when day is 1 or 2?
>
> '1052012' will be parsed as day 10, month 5, year 2012 !!!!
>
> That's not the expected behaviour! Not for me at least. I mean, in my
> case, month will always be a 2 digit string, so there's no ambiguity
> problem by pretending that... say '1052012' is correctly parsed.
>
> Is there a way out of here? I know I can pre-parse the string and
> append a '0' to it when lenght == 7, but I think that a better way
> would be if strptime allowed me to define my format in a better
> way... To say that the month is the optional one-two digit part is
> just a default, isn't it? Why can't I specify that the day part is the
> one with one-or-two digits on the input string...?
>
> Or is there a way out that I don't know yet?
>
You could just right-justify the string to 8 characters, padding with
'0':

 >>> '1052012'.rjust(8, '0')
'01052012'



More information about the Python-list mailing list