You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何将日期字符串列表转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']

# 将字符串转为datetime对象列表
date_objects = [datetime.strptime(date_str, '%Y-%m-%d') for date_str in customer_date_list]

# 对datetime对象排序
sorted_date_objects = sorted(date_objects)

# 转换为目标格式的字符串列表
sorted_date_strings = [dt.strftime('%Y-%m-%d') for dt in sorted_date_objects]

print(sorted_date_strings)

运行后输出就是你需要的结果:

['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']

你之前代码的问题分析

  1. 格式字符串错误:你用了%Y, %m, %d, %H, %M,这会生成包含逗号和时分的字符串,和目标的YYYY-MM-DD格式完全不符,应该替换为%Y-%m-%d。
  2. 列表不能直接调用strftime:list1_date.strftime(...)是错误写法,strftime是单个datetime对象的方法,必须遍历列表中的每个对象逐个调用。

关键说明

strftime('%Y-%m-%d')会自动对单个数字的月份、日期补零,比如原始字符串2011-06-2转成datetime对象后,用该格式输出会变成2011-06-02,正好匹配你需要的格式要求。

内容的提问来源于stack exchange,提问作者j ton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:01:17