Reputation: 239
most of the examples useddatetime.strptime('Jun 1 2005', '%b %d %Y').date()
Convert string "Jun 1 2005 1:33PM" into datetime
which can only put one one input at a time, but I am reciving the entire string such as
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']
my expect output is
['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']
the code below: I'm making either of those code work:
list1_date_string = [datetime.strftime(fs, "%Y, %m, %d, %H, %M") for fs in list1_date]
dateStr = list1_date.strftime("%Y, %m, %d, %H, %M")
import datetime
def date_sorting_operation(input_list):
list1_date = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in input_list]
for i in range(len(list1_date)):
for i in range(len(list1_date) - 1):
if list1_date[i] > list1_date[i + 1]:
temporary = list1_date[i + 1]
list1_date[i + 1] = list1_date[i]
list1_date[i] = temporary
#list1_date_string = [datetime.strftime(fs, "%Y, %m, %d, %H, %M") for fs in list1_date]
#dateStr = list1_date.strftime("%Y, %m, %d, %H, %M")
return list1_date, type(list1_date)
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']
print (date_sorting_operation(customer_date_list))
Upvotes: 0
Views: 365
Reputation: 5456
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])
Upvotes: 1
Reputation: 532
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.
Upvotes: 1
Reputation: 860
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']
Upvotes: 1