Py学习  »  Python

如何使用python在sql select语句中插入今天的日期?

Gokkul Kumar • 6 年前 • 2093 次点击  

我试图将today变量发送到sql中,但它不起作用。

import datetime from date

today = date.today()


stmt = "select agent_email from customer_interaction_fact where to_date(DT) >= + today + ORDER BY CONVERSATION_CREATED_TIME DESC"
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40990
文章 [ 3 ]  |  最新文章 6 年前
Darren Christopher
Reply   •   1 楼
Darren Christopher    6 年前

你用的是什么数据库引擎?你需要转换python datetime 对象转换为数据库接受格式的字符串。

# In case YYYY-MM-DD
today_str = str(today)

stmt = f"""select agent_email 
           from customer_interaction_fact 
           where to_date(DT) >= datetime({today}, "YYYY-MM-DD") 
           order by CONVERSATION_CREATED_TIME DESC"""

另一种解决方案是,假设客户机(程序)与数据库引擎位于同一时区,则可以使用数据库引擎 datetime.now 功能。在 SQLite 例如 datetime('now')

Zaynul Abadin Tuhin
Reply   •   2 楼
Zaynul Abadin Tuhin    6 年前

像下面这样试试

import datetime from date

today = date.today()


stmt = "select agent_email,aht_in_secs,queueid,EFFORTSCORE from facts.public.customer_interaction_fact where agent_email <> 'Bot' and aht_in_secs is not NULL and to_date(DT) >=" + today + "ORDER BY CONVERSATION_CREATED_TIME DESC"
Selcuk
Reply   •   3 楼
Selcuk    6 年前

不用用python计算今天的日期。只需使用postgresql函数 CURRENT_DATE :

stmt = "SELECT ... WHERE TO_DATE(DT) >= CURRENT_DATE ..."