简体   繁体   English

Python3:将日期字符串按时间顺序排列

[英]Python3: Date strings to chronological order

I have a dictionary where the keys are date strings. 我有一本字典,其中的键是日期字符串。 The format is: 格式为:

%d.%m.%Y

ie. 即。 "5.11.2008". “2008年5月11日”。 The dates have corresponding data for each day. 这些日期每天都有相应的数据。

What would be the easiest way to collect them in to two lists, one for the keys and one for the values, where the lists were in chronological order and keys[5] would correspond to values[5]? 将它们收集到两个列表中的最简单方法是什么:一个用于键,一个用于值,其中列表按时间顺序排列,而键[5]对应于值[5]?

What I'm ultimately trying to achieve is get those dates and values and plot them accordingly. 我最终想要实现的是获取这些日期和值并相应地绘制它们。 I'm using matplotlib at the moment. 我目前正在使用matplotlib。

Convert the keys to datetime.date values; 将键转换为datetime.date值; using .items() would give you tuples of both key and value that you can then sort: 使用.items()将为您提供键和值的元组,然后可以对其进行排序:

data = [(datetime.datetime.strptime(k, '%d.%m.%Y').date(), v) 
        for k, v in yourdict.items()]
data.sort()

Then index these; 然后索引这些; data[5][0] is the date, data[5][1] is the dictionary value. data [5] [0]是日期,data [5] [1]是字典值。

If you need to retain the original date formatting, use the date format parsing only for sorting; 如果您需要保留原始日期格式,请仅使用日期格式解析进行排序; here's a one-liner variant of the above that uses a sort key: 这是上述使用排序键的单线变体:

data = sorted(yourdict.items(), 
              key=lambda i: datetime.datetime.strptime(i[0], '%d.%m.%Y'))

Here I use the sorted() function to do the hard work, and the key lambda takes each date string, converting it to a datetime.datetime instance for sorting purposes only. 在这里,我使用sorted()函数进行艰苦的工作, key lambda接受每个日期字符串,并将其转换为datetime.datetime实例,仅用于排序目的。 I don't limit this to a datetime.date instance as in the first example. 我不像第一个示例那样将其限制为datetime.date实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM