在Python字典中选择一系列日期

Kit*_*Kit 3 python dictionary date range

我有以下字典:

history = {
"2008-11-17": 41, 
"2010-05-28": 82, 
"2008-11-14": 47, 
"2008-11-13": 60, 
"2008-11-12": 56, 
"2008-11-11": 55, 
"2008-11-10": 98, 
"2008-11-19": 94, 
"2008-11-18": 94, 
"2004-05-27": 82, 
"2004-05-26": 45, 
"2004-05-25": 70,
# there's more ...
}
Run Code Online (Sandbox Code Playgroud)

如何定义生成器函数get_records(dict_history, str_from_date, str_to_date)以生成date: record条目?

我知道如何将datetime对象转换为我想要的任何字符串格式.但是,我在这个障碍中的主要痛点是:

  1. dicts没有订购.
  2. dict 键是字符串.
  3. 日期不是连续的.

到目前为止,这是我能想到的:

from datetime import datetime, timedelta

def get_records(history, start_date, end_date):
  fmt = "%Y-%m-%d"
  dt = timedelta(days=1)

  present_date = datetime.strptime(start_date, fmt)
  end_date = datetime.strptime(end_date, fmt)

  while present_date <= end_date:
    present_string = present_date.strftime(fmt)
    try:
      yield (present_string, history[present_string])
    except KeyError:
      pass
    present_date += dt
Run Code Online (Sandbox Code Playgroud)

有更有效的方法吗?

更新(2011年8月2日)
SortedCollection在ActiveState上找到了一个班级,也是由Raymond Hettinger编写的.

Sve*_*ach 5

我只是迭代字典并返回匹配的项目:

def get_records(history, start_date, end_date):
    for date, entry in history.iteritems():
        if start_date <= date <= end_date:
             yield date, entry
Run Code Online (Sandbox Code Playgroud)

请注意,您的特定日期格式允许直接字符串比较<,并>没有转换为datetime实例第一.

另请注意,给定的函数将以无特定顺序返回匹配项.