Python AttributeError: module ‘datetime’ has no attribute ‘strptime’ (2 Examples)

In this Python tutorial you’ll learn how to fix the AttributeError: module ‘datetime’ has no attribute ‘strptime’.

Example Data

For the basis of this Python tutorial, we’ll use the following data:

date_1 = '2019-1-26'                                # Generating example data
print(date_1)                                       # Show example data
# 2019-1-26

Example 1: Replicate the AttributeError: module ‘datetime’ has no attribute ‘strptime’

In the first example, I’ll show how to reproduce the error message: AttributeError: module ‘datetime’ has no attribute ‘strptime’.

To reach this, we have to load the datetime module as seen below:

import datetime                                     # Import datetime module to Python

Next, when trying to apply the strptime function, we receive the following output:

datetime.strptime(date_1, '%Y-%m-%d')               # Trying to apply the strptime command
# AttributeError: module 'datetime' has no attribute 'strptime'

Example 2: Solve the AttributeError: module ‘datetime’ has no attribute ‘strptime’

To get rid of the error message, we must load “from datetime import datetime” instead of “import datetime”:

from datetime import datetime                       # Load datetime

Now we can apply the strptime function, and it’s working properly:

date_1_new = datetime.strptime(date_1, '%Y-%m-%d')  # strptime works
print(date_1_new)
# 2019-01-26 00:00:00

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top