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

PyMySQL中datetime、time、timestamp对应占位符及插入问题咨询

关于PyMySQL的两个常见问题解答

一、MySQL数据类型对应的PyMySQL占位符

首先纠正一个误区:DATE类型并不用%d(%d是整数占位符),所有MySQL日期/时间类型在PyMySQL里统一用%s作为占位符,只需传入对应Python类型的对象即可:

  • INT(id这类整数类型):%i或%s都可,PyMySQL会自动转换
  • VARCHAR/TEXT(name这类字符串类型):%s
  • DATE:%s,传入Python的datetime.date对象
  • DATETIME:%s,传入Python的datetime.datetime对象
  • TIME:%s,传入Python的datetime.time对象
  • TIMESTAMP:%s,传入datetime.datetime对象,MySQL会自动处理时间戳转换

二、使用MySQL内置时间函数时的NoModuleError解决

你遇到的错误是因为把now()、current_date()这些MySQL内置函数当成了Python函数调用,Python解释器自然找不到对应的模块。

正确用法是把这些函数直接写在SQL语句字符串里,而非作为Python参数传入:

错误示例

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='xxx', db='test_db')
cursor = conn.cursor()

# 错误:将MySQL函数now()当作Python函数调用
sql = "INSERT INTO test_table (id, create_time) VALUES (%s, %s)"
cursor.execute(sql, (1, now()))
conn.commit()

正确示例

import pymysql
from datetime import datetime

conn = pymysql.connect(host='localhost', user='root', password='xxx', db='test_db')
cursor = conn.cursor()

# 方式1:直接在SQL中使用MySQL内置函数
sql = "INSERT INTO test_table (id, create_time) VALUES (%s, NOW())"
cursor.execute(sql, (1,))
conn.commit()

# 方式2:用Python生成时间对象传入
sql = "INSERT INTO test_table (id, create_time) VALUES (%s, %s)"
cursor.execute(sql, (1, datetime.now()))
conn.commit()

两种方式任选:

  • 想用MySQL服务器端的时间,就在SQL里写NOW()、CURRENT_DATE()(MySQL不区分大小写)
  • 想用Python本地时间,导入datetime模块生成对应对象,用%s占位符传入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:57:08