I am trying to convert a string representation of a date to a datetime object:
from datetime import datetime
dt = "2021-09-22"
dt = datetime.strptime(dt, "%y/%m/%d")
but get the following error:
ValueError: time data '"2021-09-22"' does not match format '%y/%m/%d'
Is my date format in the conversion wrong?
CodePudding user response:
Your
strptimeformat is separated by slashes (/), whereas in the date string it's separated by dashes (-).%yis for 2 digit dates, such as01, 02, 03 ..., you need%Yinstead for 4 digit years, such as2000, 2001, 2002 ....
Try:
dt = datetime.strptime(dt, '"%Y-%m-%d"')
