Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is it possible to call python's datetime.datetime without using ( )?

I am wondering why this works

import datetime as dt

test1 = dt.datetime
print(test)

''' prints: <class 'datetime.datetime'>'''

So as far as I understand python, to create an instance of a class you need to call it with brackets like this:

test2 = dt.datetime(2021, 12, 31)

(Calling the constructor method forces you to put in year, month and day).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

At first I thought calling datetime like in the first example (without the brackets) must be an attribute or something. But I can’t find a single standing attribute "datetime" in the class "datetime".

And the funny thing is – it doesn’t matter how you call it, because both lines lead to the same result:

test = dt.datetime
test2 = dt.datetime(2021, 12, 31)

print(test.now())
print(test2.now())

But why? What did I miss?
Thanks a lot!

>Solution :

A few things to unpack here.

import datetime as dt

This imports the datetime module and aliases it as dt. Next, dt.datetime is the class datetime inside the module dt (alias for datetime module). Finally, now() is defined as a class method so it does not need to be instantiated. Therefore, dt.datetime.now() calls the class method now of class datetime of module dt whereas the following:

date = dt.datetime(2021, 1, 1)
date.now()

Creates an instance of the datetime class and then have it access the class method now.

See the definition the datetime class within the module:

# Excerpt of datetime.py on Python 3.8.10
class datetime(date):
    @classmethod
    def now(cls, tz=None):
        "Construct a datetime from time.time() and optional time zone info."
        t = _time.time()
        return cls.fromtimestamp(t, tz)

Finally, see here what the Python reference has to say on the classmethod decorator:

A class method can be called either on the class (such as C.f()) or on
an instance (such as C().f()). The instance is ignored except for its
class.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading