- working on list of datetime to string
most of the examples useddatetime.strptime('Jun 1 2005', '%b %d %Y').date()
CodePudding user response:
You can sort the dates by converting them to datetime objects using a lambda (inline) function and using the converted datetime objects as the key for sorting.
from datetime import datetime
customer_date_list = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-01-14', '2010-12-13', '2010-01-12', '2010-2-11', '2010-02-07', '2010-12-02', '2011-11-30']
customer_date_list.sort(key = lambda date: datetime.strptime(date, '%Y-%m-%d'))
print(customer_date_list)
# output : ['2010-01-12', '2010-01-14', '2010-02-07', '2010-2-11', '2010-12-02', '2010-12-13', '2011-02-04', '2011-06-2', '2011-08-05', '2011-11-30']
CodePudding user response:
Given that the dates you receive are in the format YYYY-MM-DD... Why not simply sort them as strings if you just want to order them?
sorted(customer_date_list)
Would give you the output you want.
CodePudding user response:
You can try:
from datetime import datetime
customer_date_list = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-01-14', '2010-12-13', '2010-01-12', '2010-2-11', '2010-02-07', '2010-12-02', '2011-11-30']
# using only text functions
sorted(['-'.join([y.zfill(2) for y in x.split('-')]) for x in customer_date_list])
# with date conversion
sorted([datetime.strptime(x, '%Y-%m-%d').strftime('%Y-%m-%d') for x in customer_date_list])