Different output structure for datetime objects and other objects

I noted that when you display a datetime object it also used to display the module and class to which it belong along with the value stored in the object. but if you use print screen to display the object it displays only the value stored in the object.

have not seen this behaviour in other objects like string, int or float. when you display a variable or print the variable it always just displays the value stored in it. Why it differs when we print datetime objects. any insights on this is greatly appreciated.

example below

image

Hey, Keerthi.

As you know, objects usually have methods. A couple of these methods are responsible for what an object “looks like”. They are object.__repr__ and object.__str__.

It seems to be the case that when you’re in the shell and you run something that looks like the following code snippet, it will print object_placeholder.__repr__().

>>> object_placeholder

I don’t know this for a fact, I couldn’t find documentation about how Python interacts with interactive shells in this regard. However, experience and a few tests lead to believe this is the case.

Now assuming the above is true, let’s read from the documentation:

In short, object.__repr__ is for computers, object.__str__ is for humans and when you use the print function it will use the latter.

What happens with dt in your screenshot (by the way, it’s better if you post code as it facilitates reproducing your steps), is that it is an object in which object.__repr__ and object.__str__ do not match:

>>> print(dt.__repr__())
datetime.datetime(2019, 11, 2, 11, 48)
>>> print(dt.__str__())
2019-11-02 11:48:00

Where as with ints, they do match:

>>> print(a.__repr__())
5
>>> print(a.__str__())
5

Hope this helps.

2 Likes

@Bruno you have explained it very beautifully. thank you so much.

1 Like