在Python中从列表中获取没有今天日期的所有值

时间:2018-06-28 14:43:21

标签: python database list datetime

我正在连接到数据库并检索摄像机列表及其各自的ID。然后,我遍历此列表并获取上次捕获的这些图像的当前时间。我想找到在今天的日期(2018-06-28)尚未捕获的所有摄像机及其各自的ID。

import psycopg2
import os
import datetime

DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='allow').cursor()

all_cameras_query = "SELECT cameraid, name, url, latitude, longitude FROM cameras ORDER BY cameraid"
conn.execute(all_cameras_query)
all_cameras = conn.fetchall()

current_date = datetime.datetime.today().strftime('%Y-%m-%d')

last_updated_list = []

for camera in all_cameras:
    last_updated_query = "SELECT cameraid, curr_time FROM images WHERE cameraid=%d ORDER BY curr_time DESC" % (
        camera[0])
    conn.execute(last_updated_query)
    last_updated_list.append(conn.fetchall())


print(last_updated_list)

last_updated_list打印出每个cameraid和上次捕获时间的列表。现在,使用python列表和搜索,我想使用current_date来获取今天所有不是 的相机。

[(185, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(186, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(187, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(188, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(189, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(190, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(191, datetime.datetime(2018, 6, 28, 10, 1, 27))], [(192, datetime.datetime(2018, 6, 28, 10, 1, 28))], [(193, datetime.datetime(2018, 6, 28, 10, 1, 28))], [(194, datetime.datetime(2018, 6, 28, 10, 1, 28))], [(195, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(196, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(197, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(198, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(199, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(200, datetime.datetime(2018, 6, 28, 10, 1, 29))], [(201, datetime.datetime(2018, 6, 28, 10, 1, 29))]]

我不太确定如何使用此列表并对其进行操作以获取这些相机ID和所需的日期。

1 个答案:

答案 0 :(得分:4)

将今天的日期定义为

import datetime
today = datetime.date.today()

然后遍历列表并将所有非今天的项目保存到新列表中

new_list = [it for it in last_updated_list if it[0][1].date() != today]

在您的示例中,所有物品都是从今天开始的,因此您得到一个空列表

print(new_list)
[]