32

When I input the simple code:

import datetime
datetime.utcnow()

, I was given error message:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    datetime.utcnow()
AttributeError: 'module' object has no attribute 'utcnow'

But python's document of utcnow is just here: https://docs.python.org/library/datetime.html#datetime.datetime.utcnow. Why does utcnow not work in my computer? Thank you!

twasbrillig
  • 17,084
  • 9
  • 43
  • 67
user2384994
  • 1,759
  • 4
  • 24
  • 29

1 Answers1

70

You are confusing the module with the type.

Use either:

import datetime

datetime.datetime.utcnow()

or use:

from datetime import datetime

datetime.utcnow()

e.g. either reference the datetime type in the datetime module, or import that type into your namespace from the module. If you use the latter form and need other types from that module, don't forget to import those too:

from datetime import date, datetime, timedelta

Demo of the first form:

>>> import datetime
>>> datetime
<module 'datetime' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/lib-dynload/datetime.so'>
>>> datetime.datetime
<type 'datetime.datetime'>
>>> datetime.datetime.utcnow()
datetime.datetime(2013, 10, 4, 23, 27, 14, 678151)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I've had a couple of occasions in complex systems, where the datetime module somehow gets trampled and datetime.utcnow() fails as datetime is None. It's not relevant to the original question but it can sometimes be an indicator of a bigger problem in large systems. – Mike Stoddart Jun 13 '18 at 13:52
  • @MikeStoddart: that'd be a different problem. Perhaps you have something running when the Python interpreter is exiting; at that point globals are being set to `None` throughout, and you'll see exactly that type of issue. – Martijn Pieters Jun 13 '18 at 17:17
  • @MartijnPieters - I think it was caused by circular imports. – Mike Stoddart Jun 14 '18 at 17:45
  • @MikeStoddart: That would usually give a different error; an `AttributeError`, usually, but not for the module object, not `None`. – Martijn Pieters Jun 14 '18 at 18:12
  • Note that the last import statement overrules the previous one. So even if you use 'from datetime import datetime' and one of the next imports, import datetime with 'import datetime' it will be imported as a module and the attribute error will still occur. – Lorenz Apr 22 '20 at 05:15
  • @Lorenz: yes, because both the type and the module are *just objects*, referenced by names in your module. `import` binds to a name in the current namespace, there is nothing special about those names from using `datetime = ...`. – Martijn Pieters Apr 26 '20 at 12:55