"import datetime" v.s. "from datetime import datetime"

codingknob picture codingknob · Mar 29, 2013 · Viewed 124.7k times · Source

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?

Answer

kindall picture kindall · Mar 29, 2013

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.