strptime() : Returns date object from input string with format details.
Date input
from datetime import datetime
str_date='2021-8-25' # date as string
dt=datetime.strptime(str_date,'%Y-%m-%d')
print(type(dt)) #
print(dt) #2021-08-25 00:00:00
Example
from datetime import datetime
str_date='28021985' # date as string
dt=datetime.strptime(str_date,'%d%m%Y')
print(dt.year,dt.month,dt.day) # 1985 2 28
# adding format
print(dt.strftime('%Y-%m-%d')) # 1985-02-28
Date with time
from datetime import datetime
str_date='2021/8/25 13:45:53' # date as string
dt=datetime.strptime(str_date,'%Y/%m/%d %H:%M:%S')
print(dt) # 2021-08-25 13:45:53
Using Microsecond
str_date='2021/8/25 13:45:53 341789' # date as string
dt=datetime.strptime(str_date,'%Y/%m/%d %H:%M:%S %f')
print(dt) # 2021-08-25 13:45:53.341789
Wrong format
In case format is not matching , then we will get ValueError.
str_date='2021-8-25' # date as string
dt=datetime.strptime(str_date,'%Y/%m/%d')
ValueError: time data '2021-8-25' does not match format '%Y/%m/%d'