AttributeError: 'datetime' module has no attribute 'strptime'

Michael picture Michael · Oct 20, 2013 · Viewed 225.5k times · Source

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?

Answer

user2555451 picture user2555451 · Oct 20, 2013

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")