的日期时间列表上
大多数使用datetime.strptime('Jun 1 2005', '%b %d %Y').date()的例子
Convert string "Jun 1 2005 1:33PM" into 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']我的预期输出是
['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']下面的代码:我正在使这些代码中的任何一个工作:
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))
代码和输出图片:

发布于 2022-09-29 09:28:45
您可以通过使用lambda (内联)函数将日期转换为datetime对象并使用转换后的datetime对象作为排序的键来对日期进行排序。
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']发布于 2022-09-29 09:40:50
如果你收到的日期是YYYY DD格式的.如果您只想对它们进行排序,为什么不简单地将它们排序为字符串呢?
sorted(customer_date_list)会给你你想要的输出。
发布于 2022-09-29 09:42:29
你可以试试:
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])https://stackoverflow.com/questions/73892994
复制相似问题