0

I have a using below code to extract date-month-year from the string of a date however it is giving me

time data '2020-05-11T04:47:54.530000' does not match format '%Y-%m-%d %H:%M:%S.%f'

error, can anyone help?

from datetime import datetime
cr_date="2020-05-11T04:47:54.530000"
datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
2
  • 2
    Replace the space with T in the format Commented May 11, 2020 at 7:53
  • this clearly is a ISO 8601 compatible string, so if you're on Python 3.7 or higher, use the built-ins, see my answer below. fromisoformat is also much faster than strptime, see here. Commented May 11, 2020 at 8:06

2 Answers 2

1

Regarding your own code just add T see the following:

    from datetime import datetime
    cr_date="2020-05-11T04:47:54.530000"

    date_object = datetime.strptime(cr_date, '%Y-%m-%dT%H:%M:%S.%f').strftime('%m/%d/%Y')

Another way to solve this is using regex ,

    import re
    from datetime import datetime

    cr_date="2020-05-11T04:47:54.530000"
    match = re.search(r'\d{4}-\d{2}-\d{2}', cr_date)
    date = datetime.strptime(match.group(), '%Y-%m-%d').date()


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

3 Comments

why so complicated and use regex? why not just split on 'T'? ;-)
@MrFuppes sorry if regex is to complex for you but its another approach to solve the issue.
Python PEP20: Simple is better than complex.
1

if you use Python 3.7 or higher, use fromisoformat:

from datetime import datetime
cr_date="2020-05-11T04:47:54.530000"

datetime.fromisoformat(cr_date)
# datetime.datetime(2020, 5, 11, 4, 47, 54, 530000)

you can strftime that however you want now, e.g.

datetime.fromisoformat(cr_date).strftime('%m/%d/%Y')
# '05/11/2020'

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.