Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using the following code to use the date in a specific format and running into following error..how to put 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' 
like image 610
user2955256 Avatar asked Nov 10 '13 07:11

user2955256


People also ask

What is Strftime and Strptime in Python?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

How do you convert a datetime object to a string in Python?

To convert datetime to string in Python, use the strftime() function. The strftime() method is a built-in method that returns the string representing date and time using date, time, or datetime object.


2 Answers

You should use 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 the datetime object from the 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' 
like image 91
falsetru Avatar answered Sep 23 '22 20:09

falsetru


you should change cr_date(str) to datetime object then you 'll change the date to the 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") 
like image 41
hichem jedidi Avatar answered Sep 19 '22 20:09

hichem jedidi