Bilal Zaib
Bilal Zaib

Reputation: 21

How to get all dates of given month from the list of dates in strings with python?

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

Answers (3)

LN_P
LN_P

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

Sunitha
Sunitha

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

Taohidul Islam
Taohidul Islam

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

Related Questions