简体   繁体   English

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

[英]NameError: name 'datetime' is not defined

I'm teaching myself Python and was just "exploring".我正在自学 Python,只是在“探索”。 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? 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
>>> 

You need to import the module datetime first:您需要先导入模块datetime

>>> import datetime

After that it works:之后它的工作原理:

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

It can also be used as below:它也可以如下使用:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM