user13412850
user13412850

Reputation: 519

python: how do I use datetime to change the format of date

I have date in string format, which looks like this

extractDate = '5/21/20' it is currently in mm/dd/yy format

I am trying to convert it to yyyymmdd format, so I should get 20200521

below is what I tried and it gives me error

from datetime import datetime
extractDate2 = datetime.strptime(extractDate, '%m/%d/%Y').strftime('%Y%m%d')

I am getting this error

ValueError: time data '5/21/20' does not match format '%m/%d/%Y'

Where am I going wrong?

thanks,

Upvotes: 0

Views: 37

Answers (1)

Chris Curvey
Chris Curvey

Reputation: 10399

you need a lowercase "y" if you're giving 2-digit years to strptime()

(protip: look into the "dateutil" library. It will save you many headaches.)

Upvotes: 2

Related Questions