我正在尝试通过使用包将记录插入mysql
数据库。python
sqlalchemy
我有datetime
在 mysql 中输入的列,这些列已经通过加载表内联命令接受了以下格式的数据:
'2013-04-03 00:05:00-05:00'
请注意,这是由pytz
python 中的模块生成的。load table inline <file_name>
使用命令通过 mysql 控制台加载具有完全相同格式的日期时间戳的 600,000 行没有问题。MySql 在加载时接受它们,但我不确定它是否维护时区信息。这对我来说真的没关系,因为我还有 3 个其他列,它们代表我感兴趣的其他时区的日期时间。所以我知道哪一列代表 EST/EDT 或 CST/CDT,如果我愿意,我可以根据它进行查询. 我不会在 mysql 中进行任何时区转换,因为我已经有代表感兴趣时区的列。
这是按照mysql的文档:
The DATETIME type is used for values that contain both date and time parts. MySQL
retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported
range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
问题是该pytz
模块在我尝试插入的日期时间戳中提供有关时区的信息。我实际上有 4 列(EST, UTC, EST/EDT and CST/CDT)
,所以它们的时区信息都嵌入在日期时间戳中。
注意我没有使用自定义INSERT
查询。这是 sqlalchemy 执行多次插入的默认方式:
执行插入的函数如下所示:
def insert_data(data_2_insert, table_name):
# Connect to database using SQLAlchemy's create_engine()
engine = create_engine('mysql://blah:blah@localhost/db_name')
# Metadata is a Table catalog.
metadata = MetaData()
my_table = Table(table_name, metadata, autoload=True, autoload_with=engine)
column_names = tuple(c.name for c in my_table.c)
final_data = [dict(zip(column_names, x)) for x in data_2_insert]
ins = my_table.insert()
conn = engine.connect()
conn.execute(ins, final_data)
conn.close()
错误信息:
Traceback (most recent call last):
File "script.py", line 191, in <module>
main()
File "script.py", line 39, in main
insert_data(file_csv, table_name)
File "script.py", line 58, in insert_data
conn.execute(ins, final_data)
File "/usr/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 824, in execute
return Connection.executors[c](self, object, multiparams, params)
File "/usr/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 874, in _execute_clauseelement
return self.__execute_context(context)
File "/usr/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 894, in __execute_context
self._cursor_executemany(context.cursor, context.statement, context.parameters, context=context)
File "/usr/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 960, in _cursor_executemany
self._handle_dbapi_exception(e, statement, parameters, cursor, context)
File "/usr/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 931, in _handle_dbapi_exception
raise exc.DBAPIError.instance(statement, parameters, e, connection_invalidated=is_disconnect)
sqlalchemy.exc.OperationalError: (OperationalError) (1292, "Incorrect datetime value: '2013-04-03 00:05:00-05:00' for column 'rtc_date_est' at row 1")