Reputation: 1847
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!
Upvotes: 39
Views: 59545
Reputation: 1090
Please note that, the method "utcnow" in class "datetime" is now deprecated and will be removed in a future version.
You can use the following instead:
from datetime import datetime, timezone
datetime.now(timezone.utc)
Source Python 3.12 release note.
Upvotes: 7
Reputation: 1123400
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)
Upvotes: 83