Module time has no attribute clock ошибка

I have written code to generate public and private keys. It works great at Python 3.7 but it fails in Python 3.8. I don’t know how it fails in the latest version. Help me with some solutions.

Here’s the Code:

from Crypto.PublicKey import RSA


def generate_keys():
    modulus_length = 1024
    key = RSA.generate(modulus_length)
    pub_key = key.publickey()
    private_key = key.exportKey()
    public_key = pub_key.exportKey()
    return private_key, public_key


a = generate_keys()
print(a)

Error in Python 3.8 version:

Traceback (most recent call last):
  File "temp.py", line 18, in <module>
    a = generate_keys()
  File "temp.py", line 8, in generate_keys
    key = RSA.generate(modulus_length)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/PublicKey/RSA.py", line 508, in generate
    obj = _RSA.generate_py(bits, rf, progress_func, e)    # TODO: Don't use legacy _RSA module
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/PublicKey/_RSA.py", line 50, in generate_py
    p = pubkey.getStrongPrime(bits>>1, obj.e, 1e-12, randfunc)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 282, in getStrongPrime
    X = getRandomRange (lower_bound, upper_bound, randfunc)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 123, in getRandomRange
    value = getRandomInteger(bits, randfunc)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 104, in getRandomInteger
    S = randfunc(N>>3)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 202, in read
    return self._singleton.read(bytes)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 178, in read
    return _UserFriendlyRNG.read(self, bytes)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 129, in read
    self._ec.collect()
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 77, in collect
    t = time.clock()
AttributeError: module 'time' has no attribute 'clock'

Table of Contents
Hide
  1. What is AttributeError: module ‘time’ has no attribute ‘clock’?
  2. How to fix AttributeError: module ‘time’ has no attribute ‘clock’?
    1. Solution 1 – Replace time.clock() with time.process_time() and time.perf_counter()
    2. Solution 2- Upgrade the module to the latest version
    3. Solution 3 – Replace the module with another alternate
    4. Solution 4 – Downgrade the Python version
  3. Conclusion

The time.clock() method has been removed in Python 3.8 onwards. Hence if you are using the clock() method in Python 3.8 or above, you will get AttributeError: module ‘time’ has no attribute ‘clock’.  

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

The time.clock() method has been deprecated from Python 3.8 onwards, which leads to an AttributeError: module ‘time’ has no attribute ‘clock’ if used in the code.

If you are not using the clock() method but still facing this error, that means you are using some of the Python libraries such as PyCryptosqlalchemy, etc., that internally use time.clock() method.

Let us try to reproduce the error in Python 3.8

import time

print(time.clock())

Output

AttributeError: module 'time' has no attribute 'clock'

How to fix AttributeError: module ‘time’ has no attribute ‘clock’?

There are multiple solutions to resolve this AttributeError and the solution depends on the different use cases. Let us take a look at each scenario.

Solution 1 – Replace time.clock() with time.process_time() and time.perf_counter()

Instead of the time.clock() method, we can use an alternate methods such as time.perf_counter() and time.process_time() that provides the same results.

Let us take an example to see how this can be implemented.

The time.perf_counter() function returns a float value of time in seconds i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. 

import time

# perf_counter includes the execution time and the sleep time
start_time = time.perf_counter()
time.sleep(4)
end_time = time.perf_counter()

print("Elapsed Time is ", end_time-start_time)

Output

Elapsed Time is  4.0122200999903725

The time.process_time() method will return a float value of time in seconds. The time returned would be the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. 

import time

# perf_counter includes the execution time and the sleep time
start_time = time.process_time()
for i in range(1000):
    print(i, end=' ')
end_time = time.process_time()

print("Elapsed Time is ", end_time-start_time)

Output

Elapsed Time is  0.015625

Solution 2- Upgrade the module to the latest version

If you are directly using the time.clock() method in your code, then some of the external modules that you are using would be using it internally, and hence you are getting this error.

If you use a module like SQLAlchemy, upgrade it to the latest version using the below command.

pip install <module_name> --upgrade
pip install SQLAlchemy --upgrade

Solution 3 – Replace the module with another alternate

If you are using the modules like PyCrypto, there is no way you can upgrade it as it is not maintained actively.

In this case, you need to look for an alternate module like  PyCryptodome that supports the same functionality. 

# Uninstall the PyCrypto as its not maintained and install pycryptodome 
pip3 uninstall PyCrypto 
pip3 install pycryptodome 

Solution 4 – Downgrade the Python version

It is not a recommended approach to downgrade Python. However, if you have recently upgraded the Python version to 3.8 or above and facing this issue, it is better to revert or downgrade it back to the previous version until you find a solution or implement any of the above solutions.

Conclusion

The AttributeError: module ‘time’ has no attribute ‘clock’ occurs if you are using the time.clock() method in the Python 3.8 or above version. Another reason could be that you are using an external module that internally uses time.clock() function.

We can resolve the issue by using alternate methods such as time.process_time() and time.perf_counter() methods. If the issue is caused due to external modules, it is better to upgrade the module or find an alternative module if the module provides no fix.

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.

I have written code to create a ChatBot using HTML & python. I used python 3.8 but it fails when I tried to execute the form. I don’t know how it fails because I used the latest version of python. I also tried some solutions published, but they also didn’t work for me well. Help me with some solutions.

Here’s the Code:

app.py


    #import files
    from flask import Flask, render_template, request
    from chatterbot import ChatBot
    from chatterbot.trainers import ChatterBotCorpusTrainer
    from chatterbot.trainers import ListTrainer

    app = Flask(__name__)

    bot = ChatBot("Python-BOT")

    trainer = ListTrainer(bot)
    trainer.train(['what is your name?', 'My name is Python-BOT'])
    trainer.train(['who are you?', 'I am a BOT'])

    trainer = ChatterBotCorpusTrainer(bot)
    trainer.train("chatterbot.corpus.english")


    @app.route("/")
    def index():
        return render_template('index.html')


    @app.route("/get")
    def get_bot_response():
        userText = request.args.get('msg')
        return str(bot.get_response(userText))


    if __name__ == "__main__":
        app.run()


index.html


    <!DOCTYPE html>
    <html>
      <head>
        <title>Python-BOT</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <style>
          * {
            box-sizing: border-box;
          }
          body,
          html {
            height: 100%;
            margin: 0;
            font-family: Arial, Helvetica, sans-serif;
          }
          #chatbox {
            margin-left: auto;
            margin-right: auto;
            width: 40%;
            margin-top: 60px;
          }
          #userInput {
            margin-left: auto;
            margin-right: auto;
            width: 40%;
            margin-top: 60px;
          }
          #textInput {
            width: 90%;
            border: none;
            border-bottom: 3px solid black;
            font-family: monospace;
            font-size: 17px;
          }
          .userText {
            color: white;
            font-family: monospace;
            font-size: 17px;
            text-align: right;
            line-height: 30px;
          }
          .userText span {
            background-color: #808080;
            padding: 10px;
            border-radius: 2px;
          }
          .botText {
            color: white;
            font-family: monospace;
            font-size: 17px;
            text-align: left;
            line-height: 30px;
          }
          .botText span {
            background-color: #4169e1;
            padding: 10px;
            border-radius: 2px;
          }
          #tidbit {
            position: absolute;
            bottom: 0;
            right: 0;
            width: 300px;
          }
          .boxed {
            margin-left: auto;
            margin-right: auto;
            width: 78%;
            margin-top: 60px;
            border: 1px solid green;
          }
        </style>
      </head>
      <body>
        <div>
          <h1 align="center">
            <b>Welcome to Python-BOT</b>
          </h1>
        </div>
      </body>
    </html>


And this is the error I got when I tried to execute the result in Python 3.8 version


    F:Projectspython_projectsChatBot-sample-3>"F:/Installed Software/python/phython 3.8/python.exe" f:/Projects/python_projects/ChatBot-sample-3/app.py   
    Traceback (most recent call last):
      File "f:/Projects/python_projects/ChatBot-sample-3/app.py", line 9, in <module>
        bot = ChatBot("Python-BOT")
      File "C:UsersAMASHI SANDUNIKAAppDataRoamingPythonPython38site-packageschatterbotchatterbot.py", line 34, in __init__
        self.storage = utils.initialize_class(storage_adapter, **kwargs)
      File "C:UsersAMASHI SANDUNIKAAppDataRoamingPythonPython38site-packageschatterbotutils.py", line 54, in initialize_class
        return Class(*args, **kwargs)
      File "C:UsersAMASHI SANDUNIKAAppDataRoamingPythonPython38site-packageschatterbotstoragesql_storage.py", line 22, in __init__
        from sqlalchemy import create_engine
      File "C:UsersAMASHI SANDUNIKAAppDataRoamingPythonPython38site-packagessqlalchemy__init__.py", line 8, in <module>
        from . import util as _util  # noqa
      File "C:UsersAMASHI SANDUNIKAAppDataRoamingPythonPython38site-packagessqlalchemyutil__init__.py", line 14, in <module>
        from ._collections import coerce_generator_arg  # noqa
      File "C:UsersAMASHI SANDUNIKAAppDataRoamingPythonPython38site-packagessqlalchemyutil_collections.py", line 16, in <module>
        from .compat import binary_types
      File "C:UsersAMASHI SANDUNIKAAppDataRoamingPythonPython38site-packagessqlalchemyutilcompat.py", line 264, in <module>
        time_func = time.clock
    AttributeError: module 'time' has no attribute 'clock'

Python has several modules that serve different purposes, such as math module, NumPy, pandas, etc. For displaying times in various representations, the “time” module is used in Python. A function named “clock()” from the time module has been removed from Python “3.8” and later versions. So accessing this function in the latest version of Python causes the “AttributeError”. To resolve this error, you can use any alternative function in a Python program.

This post will show various reasons and solutions for Python’s “Module time has no attribute clock” error. This python blog will cover the following content:

  • Reason 1: Using the clock() Function in the Latest Version of Python
  • Solution 1: Use time.perf_counter() or time.process_time() functions
  • Solution 2: Update the Unmaintained Module

So, let’s get started with the reason.

Reason: Using the clock() Function in the Latest Version of Python

The prominent reason which causes this error in Python is when the user tries to use the “clock()” function in the latest version of Python (i.e., 3.8 and later):

The above snippet shows the error because the clock() function does not exist in the latest Python version.

Solution 1: Use time.perf_counter() or time.process_time() functions

To resolve this particular error in Python, use the “time.perf_counter()” or “time.process_time()” functions.

The function “time.perf_counter()” retrieves a float value representing the total seconds and milliseconds. This function is also used to find the execution time of a program. Let’s understand it via the following example:

Code:

import time
# printing the time
print(time.perf_counter())

In the above code, the “time.perf_counter” function retrieves the number of seconds of a performance counter.

Output:

The above output successfully shows the execution time of the program.

In Python, the “process_time()” function displays the entire duration (in fractional seconds) a code took to complete. Here is an example:

Code:

import time
# printing the current process time
print(time.process_time())

In the above code, the “time.process_time()” function is utilized to display the total time taken by the program.

Output:

The above output successfully shows the total time taken by the program.

Note: There is a slight difference between these two functions. For instance, the “time.perf_counter” function shows the sleeping time of the system, including the total execution time of a program. While the “time.process_time()” function does not include the sleeping time of the system and only represents the active processing time.

Solution 2: Update the Unmaintained Module (PyCrypto & SQLAlchemy )

This error also occurs when some external module, such as (PyCrypto & SQLAlchemy ) uses the old “clock()” function, which is not available in the latest Python. To update these unmaintained modules, you need to uninstall the old module or upgrade the module using the following syntax:

> pip install your_module --upgrade

In place of “your_module”, you can type the name of the module which needs to upgrade; for example, the below command upgrades the “SQLAlchemy” to the latest version:

> pip install SQLAlchemy --upgrade

For upgrading “PyCrypto” module you need to execute the below-provided commands:

> pip3 uninstall PyCrypto

Uninstall the “PyCrypto” and install the “pycryptodome” module to resolve the error:

> pip3 install pycryptodome

This is how the AttributeError module ‘time’ error can be fixed in Python.

Conclusion

The “module time has no attribute clock” error occurs when the user tries to access the “clock()” function in the latest Python version (i.e., 3.8 and later). To rectify this error, you need to use one of the “time.perf_counter()” or “time.process_time()” functions instead of the “clock” function. The error also occurs due to using unmaintained modules such as (PyCrypto & SQLAlchemy ). This article presented a detailed guide on resolving the “module time has no attribute clock” error.

Attributeerror: module time has no attribute clock occurs because of time.clock function is now deprecated in python 3.8 or later versions. Now if you are using the latest version and running the older syntax, you will get the same error. Now, what is the solution? There are two approaches to fix this issue. The First is downgrading the python version so that it supports the same syntax. The second is changing our code base with the Alternative syntax. Well in this article we are going to try both of them.

Firstly let’s discuss the alternative syntax approach.

Approach 1: Tring Alternatives for deprecated syntax –

Case 1: Using time. time as an alternative  –

Try time.time in the place of time.clock as the quickest solution. Either you can try at the beginning like this –

time.clock=time.time

or you need to change it specifically at each caller statement.

Case 2: Specific to PyCrypto module –

Secondary sometimes it is because of PyCrypto module then the first thing you should try is to uninstall the same and install PyCryptodome module as a replacement.

pip3 uninstall PyCrypto
pip3 install -U PyCryptodome

Case 3: Using time.perf_counter() or time.process_time() as alternative –

We can also use time.perf_counter() or time.process_time() as an alternative for time.clock. Actually this time.process_time() is the processor timimg which do not include I/O operations, delay , network letancy etc while calculation process time. But time.perf_counter() includes all such components.

Approach 2: Downgrading Python –

This is quite straightforward. If we are not bound to stick with any specific python version then downgrading is the easiest option to fix this issue. Go with a lower version of python like ( 3.7 or less ). Then you will not get this error.

Attributeerror module time has no attribute clock

Attributeerror module time has no attribute clock

Some of us would be thing think why time.clock is deprecated? Actually, it returns different results with different OS like ( Unix, Windows, etc) . It means it was Platform dependent function. I hope the reason and fix is clear to everyone.

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.

  • Modular voice chat ошибка переподключение
  • Monster hunter rise ошибка d3d
  • Modlook ошибка устройства 130
  • Monster hunter rise неустранимая ошибка
  • Modloader выдает ошибку что делать