Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to directly import now() from datetime.datetime submodule

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!

like image 257
Trevor Avatar asked Dec 15 '14 19:12

Trevor


People also ask

How do I import datetime now?

You can't import datetime. datetime. now directly because datetime is not a module, it is actually a class, and now is a classmethod.

How to get current date from datetime in Python?

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.

What is the difference between from datetime import datetime and import datetime?

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.


1 Answers

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.

like image 60
BrenBarn Avatar answered Sep 27 '22 21:09

BrenBarn