1

I am new to Python, and try to import a today method from datetime module

The only workable way I can figure out is:

from datetime import datetime
datetime.today()

But, I would like to make today sit in the import statement, like from os import getcwd works,

I tried the following two ways, but neither works

from datetime import datettime.today
from datetime.datetime import today
Tom
  • 5,848
  • 12
  • 44
  • 104

1 Answers1

2

today is a class method of the datetime class:

>>> from datetime import datetime
>>> type(datetime.today)
<class 'builtin_function_or_method'>

Therefore, you can't import it on its own.


If you really want, you can alias it by assigning it to your own function:

from datetime import datetime
today = datetime.today

but you may not want to do that: it's not clear anymore that today is a datetime class method, and, given the name of the method, today can be read as a variable instead of as a function.

  • Thanks @evert. `datetime.today()` means calling `today` on a class `datetime`? If so, then `today` method looks like a static method in Java, which can make ClassName.methodName call – Tom Nov 23 '17 at 06:21
  • @Tom Correct, it's (nearly) the same (I'm not familiar with static methods in Java). It can be seen as a constructor method that results in a `datetime` instance, hence it's part of the `datetime` class. Be aware, by the way, that Python has both class methods and static methods. The [answer to this question](https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner) sheds some light on their differences. –  Nov 23 '17 at 06:24