Formatting problem from string to Datetime

Question:

I’m trying to parse a string with the datetime standard library module and then display it.

When I try this code, the output looks correct:

>>> import datetime
>>> endDate = datetime.datetime.strptime("2022-05-03", '%Y-%m-%d').date()
>>> print(endDate)
2022-05-03

But it changes if the endDate is put into a list or tuple:

>>> print([endDate])
[datetime.date(2022, 5, 3)]

Why does the output have the "datetime.date" text?

Asked By: yatta

||

Answers:

>>> from datetime import datetime
>>> endDate = datetime.strptime("2022-05-03", '%Y-%m-%d').date()

When you printed the date object, it used str representation of the date object.

>>> str(endDate)
'2022-05-03'

When you included that in a container and printed it, the container internally uses repr representation of the object

>>> repr(endDate)
'datetime.date(2022, 5, 3)'

print function by default converts all the objects passed to it to a String with str.

All non-keyword arguments are converted to strings like str() does


To understand this better, we can create a class which implements both __str__ and __repr__ functions like this

>>> class Test:
...     def __str__(self):
...         return "TEST_FROM_STR"
...     
...     def __repr__(self):
...         return "TEST_FROM_REPR"
... 

Now, we can create instances of that class and print them separately and with list, like this

>>> Test()
TEST_FROM_REPR
>>> [Test()]
[TEST_FROM_REPR]
>>> print(Test())
TEST_FROM_STR
>>> print([Test()])
[TEST_FROM_REPR]
Answered By: thefourtheye
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.