How do I handle "out of range" warnings for timezone-aware datetime
objects on MySQL with and without SQLAlchemy
I receive a warning from Mysql-Python when inserting a timezone-aware
datetime object into a DateTime column on MySQL:
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)
The code for the test looks like this:
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")
With the full output being:
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
I am using SQLAlchemy in my original application but since this is a
problem below SQLAlchemy I am interested in solutions for both with SA and
without.
No comments:
Post a Comment