You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从格式为%Y-%m-%d %H-%M-%S的列中筛选当日数据行?

问题与解决方案

数据表结构

table_id    id_from_other_table    date_time_when_this_row_was_added
1           200                    '2023-01-06 08-11-21'
2           200                    '2023-01-07 07-21-21'
3           200                    '2023-01-07 08-10-10'

其中date_time_when_this_row_was_added列由datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")生成,时间部分用横杠分隔。需求是筛选出id_from_other_table为指定值(如200)且创建日期为当日的数据行,当日日期通过today_date = datetime.datetime.now().strftime("%Y-%m-%d")获取。

原有查询失败原因

  1. LIKE匹配查询失败:SQL语句中date_time_when_this_row_was_added LIKE ?%的写法错误,参数化查询里不能直接在?后拼接%,会触发语法错误,无法正确匹配日期前缀。
  2. DATE函数转换查询失败:数据库的DATE()函数无法识别横杠分隔的时间格式(如08-11-21),无法将字符串转换为有效日期类型,导致匹配失效。

正确解决方案

方案1:修复LIKE查询的参数拼接

把通配符%与日期参数整合,确保SQL语法合法:

import datetime

id = 200
today_date = datetime.datetime.now().strftime("%Y-%m-%d")
# 方法:将通配符直接加到参数值中
query = 'SELECT * FROM table WHERE id_from_other_table = ? AND date_time_when_this_row_was_added LIKE ?'
cursor.execute(query, (id, f"{today_date}%"))

也可根据数据库语法,在SQL中拼接通配符(比如SQLite用||,MySQL用CONCAT):

# SQLite示例
query = 'SELECT * FROM table WHERE id_from_other_table = ? AND date_time_when_this_row_was_added LIKE ? || "%";'
cursor.execute(query, (id, today_date))

方案2:字符串截取匹配日期

直接截取date_time_when_this_row_was_added的前10位(即纯日期部分)与当日日期匹配,跳过格式转换问题:

import datetime

id = 200
today_date = datetime.datetime.now().strftime("%Y-%m-%d")
# SUBSTRING/SUBSTR根据数据库调整,多数数据库通用写法
query = '''
SELECT * FROM table 
WHERE id_from_other_table = ? 
AND SUBSTRING(date_time_when_this_row_was_added, 1, 10) = ?
'''
cursor.execute(query, (id, today_date))

方案3:从根源优化——存储标准日期格式

建议插入数据时使用冒号分隔时间的标准日期格式,或直接存储datetime类型,彻底避免后续查询的格式问题:

import datetime

# 插入时用标准格式
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute('INSERT INTO table (id_from_other_table, date_time_when_this_row_was_added) VALUES (?, ?)', (200, current_time))

# 或直接存储datetime对象(数据库支持的情况下)
cursor.execute('INSERT INTO table (id_from_other_table, date_time_when_this_row_was_added) VALUES (?, ?)', (200, datetime.datetime.now()))

此时原本的DATE()函数查询即可正常工作:

query = 'SELECT * FROM table WHERE id_from_other_table = ? AND DATE(date_time_when_this_row_was_added) = ?'
cursor.execute(query, (id, today_date))

内容的提问来源于stack exchange,提问作者Erika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:30:49