Answering after OP clarified they want to keep AllDates
a list of date
objects. All the other answers have it as a list of strings
First and foremost, it is important to understand that this is just a representation thing. When you print dateinAT
inside the loop you get the output in the format that datetime.date.__str__
returns it. However, when you print the AllDates
list outside of the loop, you get each date
object in the format that datetime.date.__repr__
returns.
See Difference between __str__ and __repr__? for more info on __str__
and __repr__
.
After clearing that, and if you still think it is worthwhile to get [2020-11-06, 2018-10-26]
as the output of print(AllDates)
, this can be achieved by using a class that subclasses list
with a custom implementation of __str__
(which will use each element's __str__
method instead of __repr__
).
from collections import UserList
class DatesList(UserList):
def __str__(self):
return '[' + ', '.join(str(e) for e in self) + ']'
# as an exercise, change str(e) to repr(e) and see that you get the default output
all_dates = ['06/11/2020', '26/10/2018']
AllDates = DatesList() # <- note we use our new class instead of list() or []
for item in range(len(all_dates)):
dateinAT = datetime.strptime(all_dates[item], '%d/%m/%Y').date()
AllDates.append(dateinAT)
print(AllDates)
print([type(e) for e in AllDates])
This outputs
[2020-11-06, 2018-10-26]
[<class 'datetime.date'>, <class 'datetime.date'>]
and keeps AllDates
a list of date
objects.