AttributeError: object 'str' does not have attribute 'strftime'

I use the following code to use a date in a specific format and running the following error. How to place a date in m / d / y format?

from datetime import datetime, date def main (): cr_date = '2013-10-31 18:23:29.000227' crrdate = cr_date.strftime(cr_date,"%m/%d/%Y") if __name__ == '__main__': main() 

Error: -

 AttributeError: 'str' object has no attribute 'strftime' 
+11
source share
2 answers

You should use a datetime object, not str .

 >>> from datetime import datetime >>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227) >>> cr_date.strftime('%m/%d/%Y') '10/31/2013' 

To get a datetime object from a string, use datetime.datetime.strptime :

 >>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f') datetime.datetime(2013, 10, 31, 18, 23, 29, 227) >>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y') '10/31/2013' 
+21
source

You have to change cr_date (str) to a datetime object, then you change the date to a specific format:

 cr_date = '2013-10-31 18:23:29.000227' cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f') cr_date = cr_date.strftime("%m/%d/%Y") 
0
source

Source: https://habr.com/ru/post/957766/


All Articles