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')
R.singh
  • 259
  • 1
  • 13
  • 2
    Replace the space with `T` in the format – Zionsof May 11 '20 at 07:53
  • this clearly is a [ISO 8601](https://en.wikipedia.org/wiki/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](https://stackoverflow.com/a/61710371/10197418). – FObersteiner May 11 '20 at 08:06

2 Answers2

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'
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
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()


dt170
  • 417
  • 2
  • 12