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.
As you know, objects usually have methods. A couple of these methods are responsible for what an object “looks like”. They are
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
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:
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.__str__ do not match:
datetime.datetime(2019, 11, 2, 11, 48)
Where as with
ints, they do match:
Hope this helps.
@Bruno you have explained it very beautifully. thank you so much.