Why is `datetime.strptime()` called a constructor instead of a class method?

From the lesson -

Classes can also have additional constructors, so objects can be defined in multiple ways. The datetime class has one of these that we can use to parse dates directly from strings.

The datetime.strptime() constructor returns a datetime object

I tried to look through Python’s source code and found this -

Just about the method definition, we see the decorator @classmethod. And there’s nothing else which clearly helps me understand why this isn’t a method, but a constructor instead. So, I am not entirely sure why in the lesson it’s called a constructor, but the source code puts it differently.

Can anyone explain the distinction between the normal constructor (__init__()), other constructors (like in the lesson, strptime() is considered a constructor), and how methods and constructors truly differ?

I am also having the same query and thanks that this is already posted, could someone please help to answer this.

@Sahil I’m sorry, but don’t we get Premium Support on a Premium Plan as per https://www.dataquest.io/subscribe/?

I can understand delays in responses, especially if you are a small team. But would still prefer to get a response at some time. 3-weeks of no response seems a lot and limits what and how we can learn. Thanks.

Hi @the_doctor,

My apologies, I missed this message. Recently @sohamdey.tcs asked the same question and this was the response that I provided:

Officially, datetime.strptime() is declared as class method instead of a constructor in the source code:

However, I guess the author is talking about constructors from an abstract point of view. Basically, a constructor is a special kind of method that Python calls when it instantiates an object using the definitions found in your class. If we go into a bit more depth, there are certain conditions to be met, in order to consider a method to be a constructor. However, in abstract terms, datetime.strptime() matches with the definition. It is instantiating a datetime object.

I have confirmed this with the author. Here we have attempted to simplify that topic as providing it’s actual explanation will create even more confusion for the students. So you are right, datetime.strptime() is a class method.

Hope this helps :slightly_smiling_face:

Best,
Sahil

2 Likes