将时区感知的日期时间对象插入 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 的解决方案感兴趣。