Skip to content Skip to sidebar Skip to footer

Can't Import Import Datetime In Script

I cannot import datetime from a python script, but I can from the terminal command line. 1)import datetime 2)From datetime import datetime month = datetime.datetime.now().strftime

Solution 1:

You named your scriptdatetime.py, located at /Users/ripple/Dropbox/Python/datetime.py. This is being imported instead of the standard library module, because the directory of the main script is the first place Python looks for imports.

You cannot give your scripts the same name as a module you are trying to import. Rename your script. Make sure you also delete the bytecode cache at /Users/ripple/Dropbox/Python/datetime.pyc.

Solution 2:

Here is what is happening:

  1. you named your file datetime.py for testing
  2. then you wrote import datetime inside it, because that's the module you want to try out

What happens when you run the file, is that:

  1. Python first looks into your local directory for a module called datetime
  2. Since Python only finds your original file, it makes an empty module file called datetime.pyc, because it expects you to build upon it

Luckily, the nice people at StackOverflow made you aware of this naming error, and you renamed your datetime.py file to something else. But confusingly you still get errors and the frustration slowly builds...

Answer :

  1. Always make sure that your filenames aren't equal to any Python module you want to import
  2. If you still forget, then make sure to delete or rename both the local .py script and the local .pyc file. This should fix your problem. :)

The reason this is such a common error, is that people like testing stuff when programming. And when they do, the natural inclination of most people is to make a script with the same name as the thing they want to test. However that's one of the first gotchas most Python developers run into. If the cool people that designed Python read Donald Norman before making their system, this would never be a problem. But as it is, we just have to adjust to how the Python module system works before naming our files. Note: There are still reasons for the Python module system working this way, however that doesn't preclude it from being confusing to beginners.

Solution 3:

Your second line is overwriting what python understands the word 'datetime' to mean in later code. You should either use

import datetime                 # the complete module
month = datetime.datetime.now().strftime("%B")

or

from datetime import datetime   # one part of the main modulemonth= datetime.now().strftime("%B")

Solution 4:

while saving the scripts make sure you give it different name (other than date time) and save it in c:/Python34/Scripts; i' m sure this will work then.

Post a Comment for "Can't Import Import Datetime In Script"