Reputation: 21
I want to get all the dates with given year-month but it give incorrect results. What could be the better way to get all dates on given year-month?
d = ['2006-12-30', '2006-12-31', '2006-1-1', '2006-11-30', '2006-10-1','2006-9-30']
key = '2006-1'
[i for i in d if key in i]
It gives output
['2006-12-30', '2006-12-31', '2006-1-1', '2006-11-30', '2006-10-1']
while I need
['2006-1-1']
Advance thanks for any help?
Upvotes: 1
Views: 174
Reputation: 1488
Maybe there is a nicer way but that checks for all dates between the 01.01.2006 and the 31.01.2006
import datetime
d = ['2006-12-30', '2006-12-31', '2006-1-1', '2006-11-30', '2006-10-1','2006-9-30']
dates_list = [datetime.datetime.strptime(date, '%Y-%m-%d').date() for date in d]
low = datetime.datetime.strptime('2006-01-01', '%Y-%m-%d').date()
up = datetime.datetime.strptime('2006-01-31', '%Y-%m-%d').date()
within = [date for date in dates_list if low <= date <= up]
print(within)
Upvotes: 0
Reputation: 12025
Change your key from 2006-1
to 2006-1-
>>> d = ['2006-12-30', '2006-12-31', '2006-1-1', '2006-11-30', '2006-10-1','2006-9-30']
>>> key = '2006-1-'
>>> [i for i in d if key in i]
['2006-1-1']
But a better way to do that would be to convert the string to datetime
object and then make the decision
>>> from datetime import datetime
>>> [i for i in d if datetime.strptime(i, '%Y-%m-%d').strftime('%Y-%m') == '2006-01']
['2006-1-1']
Upvotes: 4
Reputation: 5424
In your case 2006-1
is in both 2006-1
and 2006-12
.That's why you're not getting your expected answer.
You can try this:
d = ['2006-12-30', '2006-12-31', '2006-1-1', '2006-11-30', '2006-10-1','2006-9-30']
key = '2006-1'
output= [i for i in d if i.split("-")[0]==key.split("-")[0] and i.split("-")[1]==key.split("-")[1]]
print(output)
Upvotes: -1