Extract day from date string in a list

Question:

How can I extract only the day from a list such as this?

date_data = [None, None, None, None, '2014-01-05', '2014-01-06', '2014-01-07', None, None, '2014-01-10']

I’ve tried a few different lambda functions such as:

Date_List = [d for y, m, d in map(lambda x: str(x).split('-'), date_data) if y != None if m != None if d != None]

or

test = [datetime.strptime(i, '%Y-%m-%d') for i in date_data]
test1 = [datetime.strftime(i, '%d') for i in test]

But I cannot get the correct output which is:

date_data = [None, None, None, None, '05', '06', '07', None, None, '10']

Does someone know how to accomplish this?

Asked By: Rettro

||

Answers:

Based on your initial run though you could do this:

Date_List = [x.split('-')[2] if x else None for x in date_data] 

which goes through the list elements and appends a none if the element is a none to begin with and if its an element then you can get the day

Answered By: Andrew Ryan

Once you’ve used strptime to get a datetime object, you can call the day property to retrieve the value you’re looking for. I’d encourage that over string parsing based on the location of hyphens because it’s more robust to volatile input data.

from datetime import datetime

dates = [None, None, None, None, '2014-01-05', '2014-01-06', '2014-01-07', None, None, '2014-01-10']
result = []

for date in dates:
    if date is None:
        result.append(None)
    else:
        result.append(datetime.strptime(date, '%Y-%m-%d').day)

print(result)  # [None, None, None, None, 5, 6, 7, None, None, 10]
Answered By: Jamie.Sgro

Here’s a quick list comprehension that gets the job done

new_list = [i.split("-")[-1] if "-" in str(i) else i for i in list]

[None, None, None, None, '05', '06', '07', None, None, '10']

Just loops through your original list and if there’s a – in the string version of the element in splits on – and writes the last element.

Answered By: unltd_J