简体   繁体   中英

AttributeError: 'str' object has no attribute 'strftime' in django

I am trying to convert the date string into a specific date format but have an issue with it.

date = "2022-06-20T10:17:28-05:00" # getting date from DB
original_date = date.strptime('%m/%d/%Y %H:%M:%S')

Having error AttributeError: 'str' object has no attribute 'strptime'

strptime is a function of the datetime library and needs to be called liked this, not on the variable itself:

from datetime import datetime
original_date = datetime.strptime(date, '%m/%d/%Y %H:%M:%S')

It also looks like your format doesn't match the strptime format, I would suggest using the dateutil parser:

from dateutil import parser
original_date = parser.parse(date)

Finally, you would be better off storing any actual date in the database with a DateField or DateTimeField rather than a string.

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