Background: I have a few tight loops in a Python program that are called repeatedly, which include the datetime.datetime.now()
method, as well as the datetime.datetime.min
and datetime.datetime.max
attributes. For optimization, I would like to import them into the local namespace, avoiding the repeated, unnecessary module hierarchy name look-up, like so:
from datetime.datetime import now, min, max
However, Python complains:
Traceback (most recent call last):
File "my_code.py", line 1, in <module>
from datetime.datetime import now, min, max
ImportError: No module named datetime
Question: Why doesn't the above submodule import work?
Workaround: I can instead do this:
import datetime
dt_now = datetime.datetime.now
dt_min = datetime.datetime.min
dt_max = datetime.datetime.max
But, I'm curious why the more traditional approach does not work? Why can I not import methods and properties directly from the datetime.dateime submodule? ... And, is there any reason to avoid the above workaround (besides readability, outsmarting myself, etc.)?
Thanks!
You can't import datetime. datetime. now directly because datetime is not a module, it is actually a class, and now is a classmethod.
Example 1: Python get today's datetoday() method to get the current local date. By the way, date. today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.
datetime refers to the datetime class within the datetime module. If you do 'from datetime import datetime', you're only importing the datetime class, so when you refer to 'datetime' in your code, it's referring to the datetime class, not the whole datetime module.
datetime.datetime
is not a submodule. datetime
is a class within the datetime
module. now
is a method of that class. You can't use from...import...
to import individual methods of a class. You can only use it to import individual modules from a package, or individual objects that exist at the top level of a module.
As for your workaround, if you want shorthand, I find it more readable to do this:
from datetime import datetime as dt
dt.now()
# you can also use dt.max, dt.min, etc.
If you really want to put those methods directly in local variables, then your workaround makes sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With