Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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')

In my import statements I have the following:

from datetime import datetime
import datetime

I get the following error:

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

If I change the order of the import statements to:

import datetime
from datetime import datetime

I get the following error:

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

If I again change the import statement to:

import datetime

I get the following error:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

When you do:

from datetime import datetime
import 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

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

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...