AttributeError: module 'datetime' has no attribute 'now'
Asked Answered
H

13

83

I am learning Python on my own. Now I have encountered some problems. Below is my code which copy from the video who running well.

import datetime

print(type(datetime))
d1 = datetime.datetime.now()
print(d1)

when I running the code using Pycharm & sublime I got error. Below is the error information of sublime

<class 'module'>
Traceback (most recent call last):

  File "D:\programming\python\datetime.py", line 1, in <module>
    import datetime

  File "D:\programming\python\datetime.py", line 4, in <module>
    d1 = datetime.datetime.now()

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

below is the error information of pycharm

D:\programming\python\venv\Scripts\python.exe C:\Program Files\JetBrains\PyCharm 2018.1.2\helpers\pydev\pydevconsole.py" 63029 63030
<class 'module'>
Traceback (most recent call last):

  File "C:\Program Files\JetBrains\PyCharm 2018.1.2\helpers\pydev\pydevconsole.py", line 4, in <module>
    from _pydev_imps._pydev_saved_modules import thread

  File "C:\Program Files\JetBrains\PyCharm 2018.1.2\helpers\pydev\_pydev_imps\_pydev_saved_modules.py", line 21, in <module>
    import xmlrpc.client as xmlrpclib

  File "D:\programming\Anoconda3\lib\xmlrpc\client.py", line 134, in <module>
    from datetime import datetime

  File "D:\programming\python\datetime.py", line 4, in <module>
    d1 = datetime.datetime.now()

AttributeError: module 'datetime' has no attribute 'now'
Process finished with exit code 1

This code running well under IDLE and cmd. And it's running well when I just coding print(type(datetime)), but print double times type of datetime.

I don't know how to do, please give me some advice. Thanks.

Hemielytron answered 1/6, 2018 at 8:43 Comment(3)
Just a short info for anybody who finds himself in a similar solution. The reason for the problem can likely be one of these two: your namespace contains another (maybe own) instance of datetime which makes conflicting names as csevier explained --- or you just use the whole module instead of an instance, which can be solved by either from datetime import datetime instead of import datetime or datetime.datetime.now() instead of datetime.now() as provided here.Exasperation
I got the same error message and the cause is that I named the python file as "datetime.py". After changing and avoiding using datetime in the file name, the problem is fixed.Neoclassic
This works actually.Bite
M
73

User's own custom datetime.py module was overriding standard library, the information below is still useful to understand why that would happen. The import algorithm first checks your immediate directory. You can check that modules file path with:

print a_module.__file__

Welcome to the wild world of programming. So, I'm not sure I fully understand your question, so I will try to break some things down and leave room for you to discuss.

When you import datetime you import whats called a module. Without going into to much detail modules are what are commonly known as namespaces, they serve to create separation of attributes under a hierarchy so you dont accidentally overwrite other code on import. You can read more read about it here:

The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation. For related functionality, see also the time and calendar modules.

When you import it and run the type method on it you should see the following results:

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

The builtin type method documentation states the following:

4.12.6. Type Objects Type objects represent the various object types. An object’s type is accessed by the built-in function type(). There are no special operations on types. The standard module types defines names for all standard built-in types.

When you explicitly print that output it will be the same result:

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

Modules expose attributes on import. The attribute you are accessing is the datetime modules datetime attribute which is a class that happens to just have the same name. So when you access it looks like datetime.datetime

That class supports a method (which is also an attribute of the class, not the module) named "now". So, when you are accessing that method it looks like datetime.datetime.now() to call it.

If you wanted to simplify this heirarchy on import you could clarify that you only want the datetime class out of the datetime module:

from datetime import datetime
#and the access its now method simpler
d1 = datetime.now()

This may help with the attribute access problems, it may be a matter of confusion. If you want to clarify your problem more, please feel free to do so!

Manvil answered 3/6, 2018 at 15:41 Comment(18)
First, Thanks very much for your help. This is not help. I have ever tried this before asking for help. I have re-installed pycharm and sublime but didn't work too. I have tried another computer using sublime, this code running well. I ever doubt there is something wrong with the environment path. I have installed anaconda, java and VS code. But this code work well via IDLE and cmd. So, do you have any idea about this and the question that double printing the type information? Thanks very much.Hemielytron
Ohhh, so its only having the attribute error when being ran from an IDE? And what python version is it using?Manvil
python version is 3.65. When I ran with inner IDLE I got the right result, also the cmd. I have installed anaconda, VS code, java, pycharm and portable sublime. So is any chances the environment variables or path error?Hemielytron
Today I re-installed python, uninstalled anaconda, pycharm, and then download python 3.65-amd, also I can't run this code. print the type of datetime I got double print class module. The error after I call datetime method is the same as before, has no attribute. (All this running with sublime). So I don't know what happened.Hemielytron
Yq, thanks for the update. upon deeper inspection of your stack trace, I see that you have your IDE installed on a drive name c, and your python interpreter on d. Was this intentional? I’m not familiar with sublimes python integration, but my assumption is that you have to configure it to point to an installation of python. For sanity sake can you send the transcript of you running this code again. Line by line in the same interpreter your IDE is pointed to?Manvil
All python and pycharm and sublime installed on d. But I don't remember the where is IDE. I trying to reinstall python on C and try it again.Hemielytron
When I say IDE I mean integrated development environment. I’m using it as a catch all term for your tests on the sublime “ide” , pycharm “ide”, vs code “ide” etc. your stack trace shows several different installation locations for various things. If you could walk me through your exactl steps using sublime I could try to pinpoint what’s going on. Alternately I use vs code, and we could work off that installation for easier back and forth. Ultimately I don’t think it’s a code issue as you’ve identified I think it’s an environment issue.Manvil
<class 'module'> Traceback (most recent call last): File "D:\programming\pycharm python project\datetime.py", line 1, in <module> import datetime File "D:\programming\pycharm python project\datetime.py", line 4, in <module> d1 = datetime.datetime.now() AttributeError: module 'datetime' has no attribute 'now' [Finished in 0.4s with exit code 1]Hemielytron
are you naming the file you are working in datetime.py?Manvil
[shell_cmd: python -u "D:\programming\pycharm python project\datetime.py"] [dir: D:\programming\pycharm python project] [path: C:\programming\python\python36\Scripts\;C:\programming\python\python36\;C:\Program Files\Python36\Scripts\;C:\Program Files\Python36\;C:\Users\Administrator\AppData\Local\atom\bin] This is the error message now. I reinstalled the python on C. I run with cmd I got the error: has no attribute. I type this code with python shell, no error.Hemielytron
Dear csevier, I'm so sorry to disturb you and waste you so much time. After I read the error message and check the py documentation of the file after I change the name of the module, another py file that named datetime.py was found. After I del this file the code running well. I'm so sorry and thanks very very much for your help!Hemielytron
See how you are calling it from a different hard drive? datetime.py is located on the D: drive: "D:\programming\pycharm python project\datetime.py" while the python interpreter is on the C: drive: C:\programming\python\python36\ When you are in the python shell on the c it works correctly. My next course of action would be to set up youre own custom files to point to a vitrualenv controlled installation of python on the same drive. Lets do this from scratch. make a folder: mkdir test_date use global python 3 installation to make a virtual environment named venv:Manvil
cd test_date python -m venv venvManvil
Activate it: venv\Scripts\activate.bat this will change your environment variable to point to your local python 3 interpreter in the test_date folder drop into shell and test.Manvil
Here is my result: C:\Users\sevie\source\test_date (venv) λ which python /c/Users/sevie/source/test_date/venv/Scripts/python C:\Users\sevie\source\test_date (venv) λ python Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> d1 = datetime.datetime.now() >>> d1 datetime.datetime(2018, 6, 5, 9, 0, 10, 556862) >>> Manvil
@yq I jsut saw your ealier message! No problem at all! module datetime was overriding the standard library. A common mistake, try not to name your own modules with the same name! GOOD WORK!Manvil
Dear csevier, the problem is settled down. Thanks very much for your help! I have copied you comment and learn to do this. It's very helpful for me. Thanks very very much.Hemielytron
No Problem. I edited my answer with some helpful stuff in regards to troubleshooting that exact problem.Manvil
F
41
import datetime
datetime.datetime.now()
Farmyard answered 30/3, 2021 at 19:29 Comment(2)
it def does, when your import looks like import datetime. But instead of calling it as datetime.datetime, it's better to import it as from datetime import datetime, then you can just use it as datetime.now(). This did help to solve my noob issue though, thank you :)Intenerate
I had to convert it to a string first in order for it to work with datetime.datetime.strptime()Clawson
B
20

Check that you don't use wildcard imports

from datetime import datetime, timedelta
from some_lib import *

some_lib may have another datetime import which redefines yours

# in some_lib:
import datetime
Berger answered 18/6, 2020 at 9:5 Comment(0)
L
11

just import _datetime instead of datetime

sample code:

import _datetime

today = _datetime.date.today()

print(today)
Luxe answered 21/1, 2020 at 16:30 Comment(1)
What does this do that is different from importing datetime?Pricking
L
8

I encountered the same issue and found it is because of the poor naming in the datetime module, datetime is a sub-class within the datetime module.

I got around this by using:

import datetime
from datetime import datetime as dt


now = dt.now()
next = now + datetime.timedelta(minutes = 5)

next_time = next.strftime("%H:%M:%S")

current_time = now.strftime("%H:%M:%S")
print("MPS updated at {}, it will update again at {}".format(current_time, next_time))
Laconia answered 20/8, 2021 at 9:17 Comment(1)
You can (and should) remove your first line.Exasperation
P
3

You should try:

datetime.datetime.now()
Porosity answered 21/3, 2023 at 9:25 Comment(0)
U
2

In my case I accidentally had two import lines. Removing the second import fixed the issue.

from datetime import datetime
import datetime  # <-- Remove to make it work!

datetime.now()
Unlicensed answered 10/4, 2021 at 14:0 Comment(0)
U
2

This worked for me:

from datetime import datetime
d1 = datetime.now()
Upswing answered 22/1, 2022 at 0:1 Comment(0)
S
2

Problems like this can happen as a result of there being many datetime libraries installed .uninstall all datetime libraries and use cpythonThis will work in python 3.10

link to datetime module

import datetime as dt

currentDateTime = dt.datetime.now()
start_date = currentDateTime.date()
end_date = start_date +  datetime.timedelta(30)
Sprout answered 20/6, 2022 at 15:28 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Fronton
G
1

to eliminate this error (AttributeError: module 'datetime' has no attribute 'now') use the argument now() as

import datetime
time = datetime.datetime.now()
print(time)
Goforth answered 8/9, 2021 at 13:58 Comment(0)
R
0
import datetime

x = datetime.datetime.now()

print(x)

Okay so I have the same problem and after searching from here and there. all I did was change my program name from datetime.py to datetime example.py. and kaboom it worked.

Radioactivity answered 29/6, 2021 at 10:38 Comment(1)
And I think, the latter is the important as it solves the conflicting names as csevier explained. Small hint: avoid spaces in your file names.Exasperation
P
0

I also have faced this error, after few search I found the problem.

I had named my own file as datetime.py, and hence while importing the datetime module python searches through the immediate directory and it ended up importing this same file, and off course it couldn't find any now() method and hence throws the error.

Solution - change the current filename from datetime.py to something else or use:
import _datetime

Prescribe answered 25/7, 2021 at 12:30 Comment(0)
R
0

Faced same issue but it was because I was importing datetime twice... something like

from datetime import datetime
import time
import random
import subprocess
import shutil
from pathlib import Path
import datetime
import json
import sys
import os
import traceback
import shlex

As datetime is being imported twice but the last one is only importing datetime rather datetime.datetime.... if you remove the last import which is import datetime & keep only from datetime import datetime then you should be good...

Rosco answered 21/5, 2022 at 17:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.