【发布时间】:2013-08-17 03:04:56
【问题描述】:
在 MySQL 上的 DateTime 列中插入可识别时区的日期时间对象时,我收到来自 Mysql-Python 的警告:
test_mysql.py:13: Warning: Out of range value for column 'created_at' at row 1
cur.execute("INSERT INTO test (created_at) VALUES (%s)", now)
测试代码如下:
import MySQLdb
from datetime import datetime
from pytz import utc
conn = MySQLdb.connect(...) # connect
cur = conn.cursor()
now = datetime.utcnow()
cur.execute("CREATE TABLE test (created_at DATETIME)")
print("Test 1")
cur.execute("INSERT INTO test (created_at) VALUES (%s)", now)
now = utc.localize(now)
print("Test 2")
cur.execute("INSERT INTO test (created_at) VALUES (%s)", now)
print("Test 3")
now = now.replace(tzinfo=None)
assert now.tzinfo is None
cur.execute("INSERT INTO test (created_at) VALUES (%s)", now)
print("Tests done")
cur.execute("DROP TABLE test")
完整输出为:
Test 1
Test 2
test_mysql.py:13: Warning: Out of range value for column 'created_at' at row 1
cur.execute("INSERT INTO test (created_at) VALUES (%s)", now)
Test 3
Tests done
我在我的原始应用程序中使用 SQLAlchemy,但由于这是 SQLAlchemy 下的问题,我对使用 SA 和不使用 SA 的解决方案感兴趣。
【问题讨论】:
标签: python mysql datetime sqlalchemy