简体   繁体   中英

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,

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM