I want to change the format of strings in a list. They are dates but have been converted into strings.
I have looked all over for this solution, but there seem to only be answers for a single element.
First I make a series
Date_List = df.loc['receiveddate']
print Date_List
Element1 2015-06-26
Element2 2015-06-25
Element3 2015-06-26
Element4 2015-06-25
Element5 2015-06-25
Element6 2015-07-01
Then I convert it into a list.
Date_List = [str(i) for i in Date_List]
which gives me
['2015-06-26', '2015-06-25', '2015-06-26', '2015-06-25', '2015-06-25', '2015-07-01']
Instead, I want a list of strings that go day, month, year
['06-26-2015', '06-25-2015...etc.]
I've found that the most common suggestion is to use strftime. Trying Date_List = (datetime.datetime.strptime(i, "%B %d-%Y") for i in Date_List) Just gave me ValueError: time data '2015-06-26' does not match format '%B %d-%Y'
So I tried
Date_List = (datetime.datetime.strptime(i, "%Y-%m-%d") for i in Date_List)
This returned ['2015-06-26 00:00:00', '2015-06-25 00:00:00', '2015-06-26 00:00:00', '2015-06-25 00:00:00', '2015-06-25 00:00:00', '2015-07-01 00:00:00']
Does anybody know how to reformat the list? Or perhaps earlier, reformatting the Series? Thank you.
解决方案
You don't even need to use datetime here. Just map those objects to a function that turns them into strings and splits them on the -, then use str.format():
Date_List = ['{}-{}-{}'.format(m,d,y) for y, m, d in map(lambda x: str(x).split('-'), Date_List)]
Also, from your code snippet it looks like you want the month first, not the day.