Home > Back-end >  AttributeError: 'str' object has no attribute 'strftime' in django
AttributeError: 'str' object has no attribute 'strftime' in django

Time:08-12

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'

CodePudding user response:

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.

  • Related