Search code examples
pythontimestrptimestring-to-datetime

custom format directive for python strptime


I have to receive a string representing a date to process through time.strptime in a format similar to %d%m%Y but the thing is that when the day number is less than 10, then the day will be presented as a one digit number, not a two digits one as the %d format requires.

That means that

'8052012'

will be transalted as

day 08, month 05, year 2012

But with the string

'2052012'

strptime gives me

day 20, month 5, year 2012

instead of

day 2, month 5, year 2012

Is there a way around this default behavior? (perhaps to force that the %m should be a 2 digits number so strptime will have no option that to use what's left for the day?)

EDIT: Please note that on the input string, the month ALWAYS has two digits, even if it can be represented with a single one. The problem here is just the day that may be represented with one or two digits, depending on magnitude...


Solution

  • You know more about this data than time.strptime can know from the format strings.

    Remove the ambiguity by prepending '0' when the date-string has a length of 7.