Reputation: 59
y=[datetime.datetime,2016,4,27), datetime.datetime,2016,4,26)]
date1=[datetime.datetime,2016,4,28), datetime.datetime,2016,4,27)]
for item in y:
data2=[]
for item in data1:
if item.month==y.month and item.day==y.day:
data2.append(item.strftime('%d-%b-%y'))
This gives the error: 'list' object has no attribute 'month'. So how can I loop through a list of datetimes using the month as a condition? I'm using Python3
Upvotes: 0
Views: 79
Reputation: 46899
your python code is incomplete (brackets missing)...
one of the problems is that both your loop variables have the same name: item
.
the mentioned error comes from the fact that y
is a list and you are asking for y.month
.
i renamed y
to date0
and labelled the 2 necessary loop vars with item0
and item1
. this should work:
from datetime import datetime
date0 = [datetime(2016, 4, 27), datetime(2016, 4, 26)]
date1 = [datetime(2016, 4, 28), datetime(2016, 4, 27)]
ret = []
for item0 in date0:
for item1 in date1:
if item0.month == item1.month and item0.day == item1.day:
ret.append(item0.strftime('%d-%b-%y'))
print(ret)
(if you also want the year to be equal you could just do if item0 == item1:
).
Upvotes: 1