Skip to Content

How to Fix – NameError name ‘strftime’ is not defined

The strftime() method is a built-in function in Python’s datetime module that allows you to format dates and times as strings. However, sometimes you may encounter a NameError when trying to use this method. This error occurs when Python cannot find the strftime() method because it has not been imported or is not in the correct namespace.

fix nameerror name strftime is not defined

Fixing the NameError: name 'strftime' is not defined error

To fix the NameError: name 'strftime' is not defined error, you need to make sure that the datetime module is imported and that you are using the correct namespace when calling the strftime() method.

Here’s an example of how to import the datetime module and use the strftime() method correctly:

import datetime

now = datetime.datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)

In this example, we first import the datetime module using the import statement. We then create a datetime object using the now() method and store it in the now variable. Finally, we call the strftime() method on the now object and pass in a string format to specify how we want the date and time to be formatted.

Note that we use the datetime namespace when calling the now() and strftime() methods. This ensures that Python can find these methods and prevents the NameError from occurring.

Highlighted programs for you

Flatiron School

Flatiron School

Data Science Bootcamp
Product Design UX/UI Bootcamp

University of Maryland Global Campus

University of Maryland Global Campus

Cloud Computing Systems Master's
Digital Forensics & Cyber Investigation Master's

Creighton University

Creighton University

Health Informatics Master's

Conclusion

In summary, the NameError: name 'strftime' is not defined error occurs when Python cannot find the strftime() method because it has not been imported or is not in the correct namespace. To fix this error, you need to make sure that the datetime module is imported and that you are using the correct namespace when calling the strftime() method.

Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.