简体   繁体   中英

convert datetime to string and format

I have the following list that contains dates (but not formatted as datetime, only strings):

MyList = ['25/4/2014', '2/12/2014', '15/7/2014']

I want to sort this list from earliest date to the latest date. I put together the following code:

MyList = ['25/4/2014', '2/12/2014', '15/7/2014']
MyList2 = []
for i in MyList:
    MyList2.append(datetime.strptime(i, "%d/%m/%Y"))
SortedList = sorted(MyList2)

Result = []
for n in SortedList:
    m = n.strftime('%d/%m/%Y')
    Result.append(m)
print Result

The list gets sorted, but the problem is that the format is slightly different: ['25/04/2014', '15/07/2014', '02/12/2014']

Notice the extra "0" in the day and month numbers.

Is there any way to get the resulting list to have the original format where for example the month of April will be "4" and not "04"?

Thank you very much!

Use a key function with sorted() ; this'll parse the dates just for sorting , leaving the original values untouched:

SortedList = sorted(MyList, key=lambda d: datetime.strptime(d, "%d/%m/%Y"))

The list is then sorted on the return values of the key function instead of the values themselves. Internally, Python decorates the values (produces tuples of (key(v), None, v) , with None making sure v is not involved in breaking ties), sorts these, then un-decorates again.

Demo:

>>> from datetime import datetime
>>> MyList = ['25/4/2014', '2/12/2014', '15/7/2014']
>>> sorted(MyList, key=lambda d: datetime.strptime(d, "%d/%m/%Y"))
['25/4/2014', '15/7/2014', '2/12/2014']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM