Home > database >  Converting string to data object with strptime() not working
Converting string to data object with strptime() not working

Time:11-18

How to convert string '17 Nov 2021' into data object "20211117"?

I've tried:

_date=datetime.strptime(_dateAsString, '%Y%m%d')

but it does not work :/

CodePudding user response:

Parse to datetime object and then convert back to string with different date format as follows:

import datetime
_date = datetime.datetime.strptime("17 Nov 2021", "%d %b %Y").strftime("%Y%m%d")
# Result: '20211117'

You can review the available strftime() and strptime() format codes if it's not clear what the various codes e.g. %d and %b represent.

  • Related