排序日期字符串列表 [英] Sort list of date strings

查看:161
本文介绍了排序日期字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任意的日期字符串列表(mm-yyyy),如下所示:

I have an arbitrary list of date strings (mm-yyyy) as follows:

d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007'...]

我需要这个列表先按照年级(升序)排序,然后按月数(升序)排序..所以逻辑排序可以是:

I need this list to be sorted first by the level of years (ascending), then on the level of months (ascending)..so that the logical ordering can be:

d_ordered = ['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013' ...]

如何实现?

推荐答案

尝试这样:

import datetime
d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007']
sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))

这篇关于排序日期字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆