简体   繁体   English

Python:将日期与字典列表中的日期进行比较

[英]Python: Comparing a date to a date within list of dictionaries

I have a (large) list of dictionaires, containing tasks and their metadata extracted from Wunderlist. 我有一个(大)词典列表,其中包含任务和从Wunderlist中提取的元数据。 The name of the list is tasktotal . 列表的名称为tasktotal These dictionaries within the list look like this: 列表中的这些词典如下所示:

{'due_date': '2016-11-30', 'created_by_request_id': 'RqID:RqIDKey', 'type': 'task', 'title': 'This is a task ', 'completed': False, 'id': MYID, 'created_by_id': MYID, 'created_at': '2016-10-14T11:11:52.916Z', 'revision': 2, 'starred': False, 'list_id': MYLISTID}

I would like to compare the 'due_date' value to the current date using datetime : 我想使用datetime将'due_date'值与当前日期进行比较:

date_today = datetime.datetime.now().date()

If the dictinary is due today or any day before today, I would like to return the 'title' value from this dictionary. 如果要在今天或今天之前的任何一天到期,我想从这本字典中返回“ title”值。 I figured that the easiest way would be to create a new dictionary with all the entries that are due today, and then retrieve their 'title' values. 我认为最简单的方法是使用今天到期的所有条目创建一个新词典,然后检索其“ title”值。 So I made this search function: 所以我做了这个搜索功能:

def search(i):
    return [element for element in i if element[datetime.strptime('due_date')] >= date_today]

However, when I run this search on my tasktotal list, I get nothing returned. 但是,当我在tasktotal列表上运行此搜索时,我什么也没有返回。

print(search(tasktotal))

[]
Process finished with exit code 0

I don't understand what I am doing wrong here? 我不明白我在做什么错? Or is there maybe another more efficient way of retrieving the values that I need? 还是有另一种更有效的方法来检索我需要的值?

EDIT 1: 编辑1:

When I try the solution by @Peter, I get this error: 当我尝试@Peter的解决方案时,出现此错误:

    return [element['title'] for element in i if date_convert(element['due_date']) >= current_time]
   KeyError: 'due_date

EDIT 2: When I switch my brackets, like @James K and @RichSmith suggested, I get this error 编辑2:当我切换括号,如@James K和@RichSmith建议时,出现此错误

    return [element for element in i if datetime.strptime(element['due_date'], "%Y-%m-%d") >= date_today]
TypeError: can't compare datetime.datetime to datetime.date

The bracketing is wrong for 包围是错误的

element[datetime.strptime('due_date')]

This tries to convert the string "due_date" to a time, and then look up that in the dictionary. 这会尝试将字符串“ due_date”转换为时间,然后在字典中进行查找。 Instead you need to lookup the date, then convert it. 相反,您需要查找日期,然后将其转换。

datetime.strptime(element['due_date'], "%Y-%m-%d").date() 

If you want a list of titles returned, you can just use element['title'] . 如果要返回标题列表,可以只使用element['title']

I've not really used datetime so quickly threw together a slightly different solution, it converts the date to its timestamp so you can adjust the format if needed. 我没有真正使用过日期时间,因此很快提出了一个略有不同的解决方案,它将日期转换为时间戳,因此您可以根据需要调整格式。 To me at least, since it's comparing the numbers themselves instead of relying on datetime to do the comparison, it seems a bit more robust. 至少对我来说,由于它是在对数字本身进行比较,而不是依靠datetime时间进行比较,因此似乎更可靠。

I did a quick test and this is roughly 20-25% slower, it takes 1.25 seconds per 6k values as opposed to 1 though, so it's not too noticeable. 我做了一个快速测试,这大约慢了20-25%,每6k值需要1.25秒,而不是1,所以不太明显。

import datetime
import time

def date_convert(due_date):
    return time.mktime(datetime.datetime.strptime(due_date, "%Y-%m-%d").timetuple())

def search(i):
    current_time = 86400 * int(time.time() / 86400)
    future_date = '3000-01-01'
    return [element['title'] for element in i if date_convert(element.get('due_date', future_date)) <= current_time]

For the record, the 86400 which pops up is just to get the current time in seconds rounded to the start of the day, since that's the highest accuracy the data uses. 记录下来,弹出的86400只是以秒为单位将当前时间四舍五入到一天的开始,因为这是数据使用的最高精度。

I think you need to move your strptime. 我认为您需要移动strptime。

try: 尝试:

def search(i):
    return [element for element in i if datetime.strptime(element["due_date"]) >= date_today]

that way the element["due_date"] will fetch the date in each of your dictionaries. 这样, element["due_date"]将在您的每个词典中获取日期。

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

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