Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 704
user2384994 Avatar asked Oct 04 '13 23:10

user2384994


1 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) 
like image 194
Martijn Pieters Avatar answered Sep 20 '22 18:09

Martijn Pieters