python sorting date without using build in function sort()
, but the expect i want is
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-11-16',
'2010-11-22', '2010-11-23', '2010-11-26', '2010-12-02', '2010-12-13',
'2011-02-04', '2011-06-02', '2011-08-05', '2011-11-30']
I did read the similar problem and try to sloved it but still stock
(pic) for code and output Second version:
(Third version) Try just to use "input_list", remove "new_list" to save memory if that, how can I do so?
import datetime
def date_sorting_operation(input_list):
new_list = []
dates = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in input_list]
while input_list:
min = input_list[0]
for x in input_list:
if x < min:
min = x
new_list.append(min)
input_list.remove(min)
return new_list
customer_date_list = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30']
print (date_sorting_operation(customer_date_list))
(pic) try just to use "input_list", remove "new_list" to save memory:
CodePudding user response:
Actually your list of text dates are almost in an ISO sortable format, except that occasionally the month may be one digit instead of two. If we left pad the month with zero, sorting should work:
customer_date_list = ['2011-06-02', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30']
output = [re.sub(r'-(\d)-', r'-0\1-', x) for x in customer_date_list]
output.sort()
print(output)
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-12-02',
'2010-12-13', '2011-02-04', '2011-06-02', '2011-08-05', '2011-11-30']
CodePudding user response:
Try this
import datetime
customer_date_list = ['2011-06-02', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30']
lst = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in customer_date_list]
outLst = []
for _ in customer_date_list:
m = min(lst)
lst.remove(m)
outLst.append(m.strftime('%Y-%m-%d'))
print(outLst)
Output
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-12-02',
'2010-12-13', '2011-02-04', '2011-06-02', '2011-08-05', '2011-11-30']
AS OP says "that can I just use one list lst, which without outLst, to save on the same list. (In saving memory purpose)"
import datetime
customer_date_list = ['2011-06-02', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30']
lst = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in customer_date_list]
for i in range(len(customer_date_list)):
m = max(lst[i:])
lst.remove(m)
lst.insert(0,m.strftime('%Y-%m-%d'))
print(lst)
output
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-12-02',
'2010-12-13', '2011-02-04', '2011-06-02', '2011-08-05', '2011-11-30']