R.singh
R.singh

Reputation: 269

Extract Date-Month_year from utc format string python

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')

Upvotes: 0

Views: 1780

Answers (2)

dt170
dt170

Reputation: 445

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()


Upvotes: 1

FObersteiner
FObersteiner

Reputation: 25564

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'

Upvotes: 1

Related Questions