Ошибка module datetime has no attribute strptime

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?

Aran-Fey's user avatar

Aran-Fey

38.9k11 gold badges103 silver badges148 bronze badges

asked Oct 20, 2013 at 16:45

Michael's user avatar

2

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

answered Oct 20, 2013 at 16:46

4

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.

answered Oct 20, 2013 at 16:46

Thomas Orozco's user avatar

Thomas OrozcoThomas Orozco

52.8k10 gold badges111 silver badges116 bronze badges

1

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.

answered Mar 14, 2020 at 22:42

Kursad's user avatar

KursadKursad

1131 silver badge6 bronze badges

Values ​​may differ depending on usage.

import datetime
date = datetime.datetime.now()
date.strftime('%Y-%m-%d') # date variable type is datetime

The value of the date variable must be a string::

date = '2021-09-06'
datetime.datetime.strptime(date, "%Y-%m-%d")
str(datetime.datetime.strptime(date, "%Y-%m-%d")) # show differently

answered Sep 6, 2021 at 6:34

Ayse's user avatar

AyseAyse

5674 silver badges11 bronze badges

The solutions mentioned by the others are correct. But for me, it was a problem with another library importing datetime module for me and overriding the datetime class I was importing.
an example with tsai library:

from datetime import datetime
from tsai.all import *

This will give you the error: 'module' object has no attribute 'strptime'.

In this case, just flip the order of imports or just don’t import everything (even if the documentation does that) :

from tsai.all import *
from datetime import datetime

answered Dec 19, 2022 at 15:25

bibs2091's user avatar

bibs2091bibs2091

211 silver badge4 bronze badges

Table of Contents
Hide
  1. What is AttributeError: ‘module’ object has no attribute ‘strptime’
  2. How to resolve AttributeError: ‘module’ object has no attribute ‘strptime’
    1. Solution 1: Import the datetime module directly and access the method through its class name
    2. Approach 2 – Import the datetime class from the datetime module
  3. Conclusion

The AttributeError: ‘module’ object has no attribute ‘strptime’ occurs if you have imported the datetime module and directly if we are using the datetime.strptime() method on the datetime module. 

The datetime is a module, and it does not have the strptime() method; instead, we need to use the datetime class name, which has the method correct method and the syntax for the same is datetime.datetime.strptime() 

In this tutorial, we will look into what exactly is AttributeError: ‘module’ object has no attribute ‘strptime’ and how to resolve the error with examples.

First, let us see how to reproduce this issue and why developers face this particular issue with a simple example.

# import datetime module
import datetime

start_date = "2022-05-06"

# convert into datetime object and print
print(datetime.strptime(start_date, "%Y-%m-%d"))

Output

Traceback (most recent call last):
  File "c:PersonalIJSCodeCode.py", line 7, in <module>
    print(datetime.strptime(start_date, "%Y-%m-%d"))
AttributeError: module 'datetime' has no attribute 'strptime'

In the above example, we are importing the datetime module and trying to convert the string datetime to a datetime object using the datetime.strptime() method.

When we run the code, we get an AttributeError: module ‘datetime’ has no attribute ‘strptime’

The issue occurs because the datetime module does not have a strptime() method, and hence it is throwing an error.

The datetime module has a class name called datetime which in turn has the method strptime()

Since the module name and class name are also the same, it leads to a lot of confusion for the new developers, and they feel it’s ambiguous to use datetime multiple times.

How to resolve AttributeError: ‘module’ object has no attribute ‘strptime’

We can resolve the ‘module’ object has no attribute ‘strptime’ by using the strptime() method, which is present inside the datetime class.

There are two ways to access the strptime() method correctly.

Solution 1: Import the datetime module directly and access the method through its class name

If you are importing the datetime module directly, then the best way to resolve the error is to use datetime.datetime.strptime() method.

Syntax

datetime.datetime.strptime()

Here the first datetime is a module and the second datetime is a class which has a method strptime()

Example – 

# import datetime module
import datetime

start_date = "2022-05-06"

# convert into datetime object and print
print(datetime.datetime.strptime(start_date, "%Y-%m-%d"))

Output

2022-05-06 00:00:00

Approach 2 – Import the datetime class from the datetime module

Another way to resolve the issue is to import the datetime class directly using the syntax from datetime import datetime

Syntax

from datetime import datetime

While using the from syntax, we import the datetime class directly and using the class name; we can access all of its methods. We do not have to prefix/use the module name here.

Example –

# import datetime class from datetime module
from datetime import datetime

start_date = "2022-05-06"

# convert into datetime object and print
print(datetime.strptime(start_date, "%Y-%m-%d"))

Output

2022-05-06 00:00:00

Conclusion

The datetime module does not have the strptime() method; hence if we try to use datetime.strptime() directly we get AttributeError: ‘module’ object has no attribute ‘strptime’

We can resolve the issue using the datetime class name instead of the datetime module. An alternate way is to import the datetime class using the from keyword directly.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Attributeerror: module datetime has no attribute strptime error occurs because strptime is not directly available in datetime package. Actually, datetime has a class by the name of datetime inside the same. If we make an improper invoking statement, we get the same error. In this article, we will understand this error with a practical examples. We will also see the easiest way to fix this issue. So let’s begin.

In order to understand this error, we will firstly see a code sample and run the same. Then on the basis of that, we will understand the root cause.

import datetime
date_var = '2022-06-19'
datetime.strptime(date_var, "%Y-%m-%d")

when we run the code we get the above error.

attributeerror module datetime has no attribute strptime

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Attributeerror: module datetime has no attribute strptime error occurs because strptime is not directly available in datetime package. Actually, datetime has a class by the name of datetime inside the same. If we make an improper invoking statement, we get the same error. In this article, we will understand this error with a practical examples. We will also see the easiest way to fix this issue. So let’s begin.

In order to understand this error, we will firstly see a code sample and run the same. Then on the basis of that, we will understand the root cause.

import datetime
date_var = '2022-06-19'
datetime.strptime(date_var, "%Y-%m-%d")

when we run the code we get the above error.

attributeerror module datetime has no attribute strptime

attributeerror module datetime has no attribute strptime

Solution for module datetime has no attribute strptime –

Trick 1 :

As I already explained to you that this error is just because of the wrong caller statement. Firstly let’s quickly see the solution.

import datetime
date_var = '2022-06-19'
datetime.datetime.strptime(date_var, "%Y-%m-%d")

datetime has no attribute strptime solution

datetime has no attribute strptime solution

Here we made a small change in the code. We first use datetime module and datetime class then strptime attribute. That fixed our error. Earlier if we look closely, you will find that we directly used datetime.strptime which is ultimately calling attribute from the module. This is technically wrong. That’s why we were getting this error.

Trick 2 –

We can fix this issue by changing the import statement. Actually, we will import the class directly then the same syntax will work. Let’s see practically.

import datatime class directly

import datatime class directly

Now the question gets up why this common mistake developer does a large scale. The reason is very simple is name confusion. Typically module and the class name are usually different always. This is a bit different but technically correct too.  I hope now we are clear on how to fix this python exception.

Thanks

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

This error occurs when you import the datetime module and try to call the strptime() method on the imported module. You can solve this error by importing the datetime class using from datetime import datetime or accessing the class method using

datetime.datetime.strptime()

This tutorial will go through the error and how to solve it with code examples.


Table of contents

  • AttributeError: module ‘datetime’ has no attribute ‘strptime’
  • Example
    • Solution #1: Use the from keyword
    • Solution #2: Use datetime.datetime
  • Summary

AttributeError: module ‘datetime’ has no attribute ‘strptime’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. datetime is a built-in Python module that supplies classes for manipulating dates and times. One of the classes in datetime is called datetime. It can be unclear when both the module and one of the classes share the same name. If you use the import syntax:

import datetime

You are importing the datetime module, not the datetime class. We can verify that we are importing the module using the type() function:

import datetime

print(type(datetime))
<class 'module'>

We can check what names are under datetime using dir() as follows:

import datetime

attributes = dir(datetime)

print('strptime' in attributes)

In the above code, we assign the list of attributes returned by dir() to the variable name attributes. We then check for the strptime() attribute in the list using the in operator. When we run this code, we see it returns False.

False

However, if we import the datetime class using the from keyword and call dir(), we will see now as an attribute of the class. We can check for now in the list of attributes as follows:

from datetime import datetime

attributes = dir(datetime)

print('strptime' in attributes)
True

Example

Consider the following example, where we want to get create a datetime object from a string using the strptime() method.

import datetime

date_string = '12 January, 2004'

date_object = datetime.strptime(date_string, "%d %B, %Y")

print(date_object)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [5], in <cell line: 5>()
      1 import datetime
      3 date_string = '12 January, 2004'
----> 5 date_object = datetime.strptime(date_string, "%d %B, %Y")
      7 print(date_object)

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

The error occurs because we imported the datetime module and tried to call the strptime() method on the module, but strptime() is an attribute of the datetime class, not the module.

Solution #1: Use the from keyword

We can solve this error by importing the datetime class using the from keyword. Let’s look at the revised code:

from datetime import datetime

date_string = '12 January, 2004'

date_object = datetime.strptime(date_string, "%d %B, %Y")

print(date_object)

Let’s run the code to see the result:

2004-01-12 00:00:00

We successfully converted the date string to a datetime object.

Solution #2: Use datetime.datetime

We can also solve this error by importing the module and then accessing the class attribute using datetime.datetime, then we can call the strptime() method. Let’s look at the revised code:

import datetime

date_string = '12 January, 2004'

date_object = datetime.datetime.strptime(date_string, "%d %B, %Y")

print(date_object)

Let’s run the code to see the result:

2004-01-12 00:00:00

We successfully retrieved the current date and time as a datetime object.

Summary

Congratulations on reading to the end of this tutorial! Remember that from datetime import datetime imports the datetime class and import datetime imports the datetime module.

For further reading on AttributeErrors involving datetime, go to the articles:

  • How to Solve Python AttributeError: ‘datetime.datetime’ has no attribute ‘datetime’
  • How to Solve Python AttributeError: module ‘datetime’ has no attribute ‘now’
  • How to Solve Python AttributeError: module ‘datetime’ has no attribute ‘strftime’
  • How to Solve Python AttributeError: module ‘datetime’ has no attribute ‘combine’

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Python shows the AttributeError: module 'datetime' has no attribute 'strptime' message when you call the strptime() method directly from the datetime module.

To solve this error, you need to call the strptime() method from the datetime class instead of the datetime module.

The Python datetime module has a class that’s (mind-blowingly) also named datetime.

Suppose you have the following Python code:

import datetime

date_string = "2022-01-10"

date_object = datetime.strptime(date_string, "%Y-%m-%d")

print(date_object)

The strptime() method is defined in the datetime class, but the method is called from the datetime module in the example above.

This causes the following error:

Traceback (most recent call last):
  File ...
    date_object = datetime.strptime(date_string, "%Y-%m-%d")
AttributeError: module 'datetime' has no attribute 'strptime'

To solve this issue, you need to call the strptime() method from the datetime class.

You can import the datetime class directly from the module like this:

from datetime import datetime

date_string = "2022-01-10"

date_object = datetime.strptime(date_string, "%Y-%m-%d")  # ✅

Or you can access the class from the module as follows:

import datetime

date_string = "2022-01-10"

date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d") # ✅

This error confuses a lot of people because the class and the module have the same name.

To clarify your code, you can add an alias to your import statement as follows:

import datetime as dt

date_object = dt.datetime.strptime("2022-01-10", "%Y-%m-%d")

Aliasing the datetime module as dt helps clear things when you are reading the code.

Some people prefer to import the datetime class by using the from datetime import datetime syntax.

But this import statement binds the datetime name to the datetime class, so you won’t be able to use other classes and functions provided by the module.

Personally, I prefer to alias the datetime module to dt and make all import statements identical.

When you are handling Python code written by other people, look at the import statement at the top of the file:

  1. import datetime? It’s the module
  2. from datetime import datetime? That’s the class.

Knowing what is being imported to the code helps you to debug and fix the error.

And that’s how you solve the AttributeError: module 'datetime' has no attribute 'strptime' in Python. Good work! 👍

Понравилась статья? Поделить с друзьями:
  • Ошибка minecraft не удалось подключиться к миру
  • Ошибка modloader gta sa unknown game
  • Ошибка minecraft не могу войти
  • Ошибка modern warfare 3 unarc
  • Ошибка minecraft java net connectexception connection