Reputation: 15
I am new to python and was trying to sort the dates in a list. Below is the code that I wrote and getting
following error on the below line
#### date_object = datetime_object.date() ## list' object has no attribute 'date'
from datetime import datetime,date
lst_dates = ['01 Apr 2017', '01 Apr 2018', '01 Aug 2017', '01 Aug 2018', '01 Dec 2017', '01 Dec 2018', '01 Feb 2017', '01 Feb 2018', '01 Jan 2017', '01 Jan 2018']
datetime_object = sorted(lst_dates, key=lambda x: datetime.strptime(x, '%d %b %Y'))
date_object = datetime_object.date()
print(date_object)
Please assist in helping me understand what the issues is. Thanks
Upvotes: 0
Views: 1784
Reputation: 23556
This works just fine:
from datetime import datetime,date
lst_dates = ['01 Apr 2017', '01 Apr 2018', '01 Aug 2017', '01 Aug 2018', '01 Dec 2017', '01 Dec 2018', '01 Feb 2017', '01 Feb 2018', '01 Jan 2017', '01 Jan 2018']
datetime_object = sorted(lst_dates, key=lambda x: datetime.strptime(x, '%d %b %Y'))
#date_object = datetime_object.date() # <<-- remove this line
print(datetime_object)
testing:
>>> from datetime import datetime,date
>>> lst_dates = ['01 Apr 2017', '01 Apr 2018', '01 Aug 2017', '01 Aug 2018', '01 Dec 2017', '01 Dec 2018', '01 Feb 2017', '01 Feb 2018', '01 Jan 2017', '01 Jan 2018']
>>> datetime_object = sorted(lst_dates, key=lambda x: datetime.strptime(x, '%d %b %Y'))
>>> print(datetime_object)
['01 Jan 2017', '01 Feb 2017', '01 Apr 2017', '01 Aug 2017', '01 Dec 2017', '01 Jan 2018', '01 Feb 2018', '01 Apr 2018', '01 Aug 2018', '01 Dec 2018']
>>>
Upvotes: 0
Reputation: 1805
The problem with you code is on line #3 when you are writing
datetime_object = sorted(lst_dates, key=lambda x: datetime.strptime(x, '%d %b %Y'))
sorted function in Python returns a new python list object. If you want to check then run
type(datetime_object)
So in order to achieve what you want here you need to iterate over that list. Your final code would be something like this
from datetime import datetime,date
lst_dates = ['01 Apr 2017', '01 Apr 2018', '01 Aug 2017', '01 Aug 2018', '01 Dec 2017', '01 Dec 2018', '01 Feb 2017', '01 Feb 2018', '01 Jan 2017', '01 Jan 2018']
datetime_obj_list = sorted(lst_dates, key=lambda x: datetime.strptime(x, '%d %b %Y'))
for datetime_object in datetime_obj_list:
datetime_object = datetime.strptime(datetime_object, "%d %b %Y")
print(datetime_object.date())
UPDATE: Here's a working sample of the code https://ideone.com/YRDQR7
Upvotes: 1
Reputation: 17
the problem is on 4th line
it should be date_object = datetime.date()
Upvotes: 0
Reputation: 101
from datetime import datetime
lst_dates = ['01 Apr 2017', '01 Apr 2018', '01 Aug 2017', '01 Aug 2018', '01 Dec 2017', '01 Dec 2018', '01 Feb 2017', '01 Feb 2018', '01 Jan 2017', '01 Jan 2018']
lst_dates.sort(key=lambda date: datetime.strptime(date, "%d %b %Y"))
print(lst_dates)
Upvotes: 2