1

Need to convert strings present in "all_dates" to date format. I am able to convert all of them to date format and print inside the loop. But unable to print them outside the loop. Can I get "AllDates" as a list of dates, not list of Strings

from datetime import datetime, date
from dateutil.relativedelta import relativedelta

all_dates = ['06/11/2020', '26/10/2018']
AllDates = []
for item in range(len(all_dates)):
    dateinAT = datetime.strptime(newdate[item], '%d/%m/%Y').date()
    print(dateinAT)
    AllDates.append(dateinAT)
print(AllDates)

Output of the above code: 2020-11-06 2018-10-26

[datetime.date(2020, 11, 6), datetime.date(2018, 10, 26)]

Required Output: [2020-11-06, 2018-10-26]

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
test_python
  • 71
  • 1
  • 7

4 Answers4

2

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.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

The print() calls the __str__method of the datetime.date object. a quick but not so sophisticated way to solve your problem would be:

AllDates.append(dateinAT.__str__())

The better version would be using the strftime method

AllDates.append(dateinAT.strftime("%Y-%m-%d"))
Nano Byte
  • 106
  • 3
  • 1
    Use `str(dateinAT)` instead of `dateinAT.__str__()`, though this might a wrong answer, since it will make `AllDates` a list of strings instead of a list of `date` objects – DeepSpace Aug 10 '20 at 18:07
0

You code store the values as datetime values. So you need to convert that to str using strftime.

So, Change this line to

dateinAT = datetime.strptime(newdate[item], '%d/%m/%Y').date()

this

dateinAT = datetime.strptime(newdate[item], '%d/%m/%Y').strftime('%Y-%m-%d')
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

Use a list comprehension:

>>> from datetime import datetime
>>> all_dates = ['06/11/2020', '26/10/2018']
>>> AllDates = [
    datetime.strptime(item, '%d/%m/%Y').date().strftime('%Y-%m-%d') for item in all_dates]
['2020-11-06', '2018-10-26']
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228