python“import datetime” v.s. “from datetime import datetime” [英] python "import datetime" v.s. "from datetime import datetime"
问题描述
我有一个脚本需要在脚本中的不同行执行以下操作:
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? Appreciate it. Thank you.
推荐答案
你的麻烦是你有一些代码,期待 datetime
要引用 datetime
模块和其他希望 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.
这篇关于python“import datetime” v.s. “from datetime import datetime”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!