Parse the string to datetime in Python (datetime.strptime)

In Python, strptime parses a string to a datetime object.

import datetime

t = datetime.datetime.strptime('Aug 7 2019', '%b %d %Y')

print(t)  # 2019-08-07 00:00:00

Aug matches %b. The second argument of strptime is the date/time format that should be the same as the format of the string. If not so, Python raises the exception.

import datetime

t = datetime.datetime.strptime('Aug 7 2019', '%d %d %Y')

# re.error: redefinition of group name 'd' as group 2; was group 1 at position 48

Aug doesn't match %d so parsing fails. Note that several spaces mean one space.

import datetime

t = datetime.datetime.strptime('Aug   7  2019', '%b %d %Y')

print(t)  # 2019-08-07 00:00:00

Python Date & Time

Python Tutorial