-2

I want to be able to convert string to date format in python. But some of the day and month are assigned to 00.

date = ['00-00-2001', '10-01-2014']

when I tried :

datetime.strptime(date[1], '%d-%m-%Y'), of course it works fine, but doing datetime.strptime(date[0], '%d-%m-%Y'), I get the following error.

time data '00-00-2001' does not match format '%d-%m-%Y'

2
  • 4
    What do you expect to get in case of a bad date? Commented Aug 11, 2016 at 5:38
  • 1
    Does 00-00-2001 really mean January 1, 2001, or does it mean something else? Commented Aug 11, 2016 at 5:51

2 Answers 2

1

According to Python Docs:

%d Day of the month as a zero-padded decimal number. 01, 02, ..., 31

%m Month as a zero-padded decimal number. 01, 02, ..., 12

None of these accept 00 as valid string.

Also see my answer at https://stackoverflow.com/a/38801552/1005215 which explains how you can use the parser from dateutil by passing a default parameter.

Sign up to request clarification or add additional context in comments.

3 Comments

How does this answer the question? Telling the OP that it cannot be done is already taken care of by the Python interpreter.
@Kartik The python interpreter doesn't tell the OP why the string didn't match the format.
Yes, I stand corrected. "Telling the OP that it is not straightforward has already been done by the Python interpreter".
0

Execute:

corrected_date = []
for d in dates:
    components = d.split('-')
    components = [str(c).zfill(2) if(int(c) > 0) else str(int(c) + 1).zfill(2) for c in components]
    corrected_date.extend(['-'.join(components)])

Now try your strftime on corrected_date.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.