pythonpython-datetime

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


Here is my Transaction class:

class Transaction(object):
    def __init__(self, company, num, date):
        self.company = company
        self.num = num
        self.date = datetime.strptime(date, "%Y-%m-%d")

And when I'm trying to instantiate it:

tr = Transaction('AAPL', 600, '2013-10-25')

I'm getting the following error:

    self.date = datetime.strptime(date, "%Y-%m-%d")
AttributeError: 'module' object has no attribute 'strptime'

How can I fix that?


Solution

  • 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")