Here is my Transaction
class:
class Transaction(object):
def __init__(self, company, num, price, date, is_buy):
self.company = company
self.num = num
self.price = price
self.date = datetime.strptime(date, "%Y-%m-%d")
self.is_buy = is_buy
And when I'm trying to run the date
function:
tr = Transaction('AAPL', 600, '2013-10-25')
print tr.date
I'm getting the following error:
self.date = datetime.strptime(self.d, "%Y-%m-%d")
AttributeError: 'module' object has no attribute 'strptime'
How can I fix that?
This question is related to
python
class
python-2.7
Use the correct call: strptime
is a classmethod of the datetime.datetime
class, it's not a function in the datetime
module.
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
As mentioned by Jon Clements in the comments, some people do from datetime import datetime
, which would bind the datetime
name to the datetime
class, and make your initial code work.
To identify which case you're facing (in the future), look at your import statements
import datetime
: that's the module (that's what you have right now).from datetime import datetime
: that's the class.I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.
Source: Stackoverflow.com