Python SQL 查询,其中时间戳在列表中



我在python中有以下查询,我通过pd.read_sql_query使用它。它工作正常。我有一个日期列表,称为日期,用于查询。

for date i in dates:
query = ('SELECT * FROM table WHERE id in'+ str(tuple(ids)) + ' AND date 
between '+"'"+str(i)+"'"+' and '+"'"+str(i)+"'")

有没有更简单的方法来查询日期,例如 ID?我想要这样的东西:

query = ('SELECT * FROM table WHERE id in'+ str(tuple(ids)) + ' AND date in' + str(tuple(dates)) + "'")

但是,这不起作用,因为日期在我的 python 列表和 sql 数据库中保存为时间戳。

我的 SQL 数据如下所示:

id  date                 variable 
A  20180101 00:00:00       1
B  20180101 00:00:00       2
B  20180501 00:00:00       3
C  20180201 00:00:00       4

我有一个格式化为字符串的 id 列表:

["B", "C"]

以及日期列表,格式为 datetime64[ns]:

[20180101 00:00:00, 20180201 00:00:00]

所需的输出为:

id  date                 variable 
B  20180101 00:00:00       2
C  20180201 00:00:00       4

你可以做很多事情,但在我看来,这将是最易读的:

def join(l):
return ",".join([f"'{x}'" for x in l])
ids_list = join(["B","C"])
dates_list = join(["20180101 00:00:00", "20180201 00:00:00"])
# below works for python 3.6+
print(f"SELECT * FROM table WHERE id in ({ids_list}) and date in ({dates_list})")
# below works for python < 3.6 (you can also use .format())
print("SELECT * FROM table WHERE id in %(ids_list)s and date in %(dates_list)s" % locals())

最新更新