社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Gokkul Kumar • 5 年前 • 1509 次点击  

我试图将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
 
1509 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Darren Christopher
Reply   •   1 楼
Darren Christopher    5 年前

你用的是什么数据库引擎?你需要转换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    5 年前

像下面这样试试

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    5 年前

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

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