Home > Net >  Date Format in Python
Date Format in Python

Time:10-03

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:

  1. Your strptime format is separated by slashes (/), whereas in the date string it's separated by dashes (-).

  2. %y is for 2 digit dates, such as 01, 02, 03 ..., you need %Y instead for 4 digit years, such as 2000, 2001, 2002 ....

Try:

dt = datetime.strptime(dt, '"%Y-%m-%d"')
  • Related