Python NameError:未定义名称“日期时间”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19934248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:00:49  来源:igfitidea点击:

NameError: name 'datetime' is not defined

pythondatetime

提问by Doug Fir

I'm teaching myself Python and was just "exploring". Google says that datetime is a global variable but when I try to find todays date in the terminal I receive the NameError in the question title?

我正在自学 Python,只是在“探索”。Google 说 datetime 是一个全局变量,但是当我尝试在终端中查找今天的日期时,我在问题标题中收到了 NameError?

mynames-MacBook:pythonhard myname$ python
Enthought Canopy Python 2.7.3 | 64-bit | (default, Aug  8 2013, 05:37:06) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> date = datetime.date.today()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'datetime' is not defined
>>> 

采纳答案by Simeon Visser

You need to import the module datetimefirst:

您需要先导入模块datetime

>>> import datetime

After that it works:

之后它的工作原理:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)