64

我正在自学 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
>>> 
4

2 回答 2

115

您需要先导入模块datetime

>>> import datetime

之后它的工作原理:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)
于 2013-11-12T16:14:32.713 回答
4

它也可以如下使用:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
于 2020-09-30T08:36:33.413 回答