How do i get the following list
[datetime.date(2011, 4, 1), datetime.date(2011, 4, 8), datetime.date(2011, 4, 16), datetime.date(2011, 5, 21)]
as
['2011-04','2011-05']
It not only convert to string but remove dups
Convert the dates to strings using datetime.date.strftime.
dates = [date.strftime('%Y-%m') for date in dates]
You can remove duplicates by converting the list to a set and then back to a list.
dates = list(set(dates))
Then combine both methods to do it all in one step.
dates = list(set([date.strftime('%Y-%m') for date in dates]))
In [43]: import datetime
In [44]: dates=[datetime.date(2011, 4, 1), datetime.date(2011, 4, 8), datetime.date(2011, 4, 16), datetime.date(2011, 5, 21)]
In [45]: set([date.strftime('%Y-%m') for date in dates])
Out[45]: set(['2011-04', '2011-05'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With