Python 将日期时间插入 MySql 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16359143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:22:56  来源:igfitidea点击:

Inserting datetime into MySql db

pythonmysqlpython-2.7

提问by Alan Coromano

I have a datetime value which is made by strptime function

我有一个由 strptime 函数生成的日期时间值

import MySQLdb
a = time.strptime('my date', "%b %d %Y %H:%M")

There is a column in MySql db of type DATETIME. When I try to insert this value into db, I, obviously, get the error of

MySql 数据库中有一个 DATETIME 类型的列。当我尝试将此值插入 db 时,显然我得到了错误

mysql_exceptions.OperationalError: (1305, 'FUNCTION time.struct_time does not exist')

INSERT INTO myTable(Date......) VALUES(time.struct_time(tm_year=2222, tm_mon=4, tm_mday=1, tm_hour=1, tm_min=2, tm_sec=4, tm_wday=1, tm_yday=118, tm_isdst=-1), ......)

How can I insert this value into db?

如何将此值插入数据库?

采纳答案by Martijn Pieters

You are now passing in a time.struct_timeobject, something MySQL knows nothing about. You'll need to format the timestamp to a format MySQL understands. Unfortunately the MySQLdblibrary doesn't do this for you.

您现在正在传入一个time.struct_time对象,MySQL 对此一无所知。您需要将时间戳格式化为 MySQL 能够理解的格式。不幸的是,MySQLdb图书馆不会为你做这件事。

It'll be easiest using the datetimemodule, but you can do this with the timemodule too:

使用该datetime模块将是最简单的,但您也可以使用该模块执行此操作time

import datetime

a = datetime.datetime.strptime('my date', "%b %d %Y %H:%M")

cursor.execute('INSERT INTO myTable (Date) VALUES(%s)', (a.strftime('%Y-%m-%d %H:%M:%S'),))

The .strftime()method call on the datetime.datetimeobject formats the information in such a way that MySQL will accept.

.strftime()上方法调用datetime.datetime对象的格式以这样的方式是,MySQL将接受的信息。

Doing the same task with just the timemodule:

仅使用time模块执行相同的任务:

import time

a = time.strptime('my date', "%b %d %Y %H:%M")

cursor.execute('INSERT INTO myTable (Date) VALUES(%s)', (time.strftime('%Y-%m-%d %H:%M:%S', a),))