AttributeError: 'module' object has no attribute 'utcnow'

Question:

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!

Asked By: user2384994

||

Answers:

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)
Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.