你的convert参数传错了。
select date_format(字段名称, '%Y-%m-%d')
dateformat(时间字段,“%y-%M-%d”)
【输入的日期格式为'year-mm-dd' 这个办法可行吗】
这个办法是不行的。
第一种方式:在sql查询语句把datetime对象转换为字符串格式
select type_name, value, date_format(create_time, '%Y-%m-%d') from data_list
在sql语句中使用 date_format 将 create_time 字段转换为字符串格式,这里可以根据需要转换为"年-月-日"等格式。
第二种方式:在python中把datetime对象转换为字符串格式
先从数据库中读出数据,然后在python中使用 strftime 方法转换为字符串
from utils.connect_db import MysqlConnect
db = MysqlConnect()
sql = "select type_name, value, create_time from data_list LIMIT 0, 5"
data = db.select_all(sql)
db.close()
# print(data)
new_data = [list(item) for item in list(data)]
print(new_data)
def list_obj(array):
obj = {"date": array[2].strftime("%Y-%m-%d %H:%M:%S"), "type": array[0], "value": array[1]}
return obj
m = map(list_obj, new_data)
print(list(m))
提问请先说明你用的那种数据库。oracle mysql mssql postgres。
哪怕你用命令行查询,也显示个版本信息用于辨别。
把convert()的部分换成 date_format(recordtime, '%Y-%m-%d')。
mysql日期格式转化参考:
https://www.w3school.com.cn/sql/func_date_format.asp
试试这条语句是否符合你的要求
select * from DateTransactionTable where date_format(RecordTIme, '%Y-%m-%d') = '2022-12-24'
看了下你的需求,其实你这么写就可以了,不用去转换为String
select * from DateTransactionTable where RecordTIme like '2022-12-24%'
你可以使用CAST函数将日期转换为字符串,然后再进行模糊搜索。例如:
SELECT * FROM table WHERE CAST(datetime_column AS VARCHAR) LIKE '%year-mm-dd%'
但是要注意,在这种情况下,查询效率可能会变差,因为SQL服务器必须将每个行的日期转换为字符串,然后再进行比较。所以最好是在数据库中存储字符串日期,这样就可以直接进行模糊搜索了。
不需要 convert
date_fomat(RecordTime,'%Y-%m-%d')
SQL 像这么写就没有问题了:
select * from DateTransactionTable
where date_format(RecordTime, '%Y-%m-%d') = '2022-12-24'
把convert()的部分换成 date_format(recordtime, '%Y-%m-%d')。
mysql日期格式转化参考:
https://www.w3school.com.cn/sql/func_date_format.asp