“导入日期时间"诉“从日期时间导入日期时间"

“导入日期时间

问题描述:

我有一个脚本,需要在脚本的不同行执行以下操作:

I have a script that needs to execute the following at different lines in the script:

today_date = datetime.date.today()
date_time = datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

在我的import语句中,我具有以下内容:

In my import statements I have the following:

from datetime import datetime
import datetime

我收到以下错误:

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

如果我将import语句的顺序更改为:

If I change the order of the import statements to:

import datetime
from datetime import datetime

我收到以下错误:

AttributeError: 'method_descriptor' object has no attribute 'today'

如果我再次将import语句更改为:

If I again change the import statement to:

import datetime

我收到以下错误:

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

这是怎么回事,我怎么都可以工作?

What is going on here and how do I get both to work?

您的麻烦是您有一些代码希望datetime引用datetime module 和其他代码.期望datetime是对datetime 类的引用的代码.显然,两者不能兼而有之.

Your trouble is that you have some code that is expecting datetime to be a reference to the datetime module and other code that is expecting datetime to be a reference to the datetime class. Obviously, it can't be both.

当您这样做:

from datetime import datetime
import datetime

首先要将datetime设置为对该类的引用,然后立即将其设置为对该模块的引用.相反,这是一回事,但最终是对该类的引用.

You are first setting datetime to be a reference to the class, then immediately setting it to be a reference to the module. When you do it the other way around, it's the same thing, but it ends up being a reference to the class.

您需要重命名这些引用之一.例如:

You need to rename one of these references. For example:

import datetime as dt
from datetime import datetime

然后,您可以将datetime.xxxx形式的引用(该引用指向该模块)更改为dt.xxxx.

Then you can change references in the form datetime.xxxx that refer to the module to dt.xxxx.

否则,只需import datetime并更改所有引用以使用模块名称.换句话说,如果只是说datetime(...),则需要将该引用更改为datetime.datetime.

Or else just import datetime and change all references to use the module name. In other words, if something just says datetime(...) you need to change that reference to datetime.datetime.

Python在它的库中有很多类似的东西.如果他们遵循 PEP 8 中的命名准则,则datetime类将被命名为Datetime,使用datetime表示模块和使用Datetime表示类都没有问题.

Python has a fair bit of this kind of thing in its library, unfortunately. If they followed their own naming guidelines in PEP 8, the datetime class would be named Datetime and there'd be no problem using both datetime to mean the module and Datetime to mean the class.