插入mysql数据库时间戳

Ste*_*son 6 python mysql insert python-2.7

我在我的python脚本中有一部分需要在下面的mysql数据库示例中将一些数据插入到表中:

insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2))
db.commit()
db.close()
Run Code Online (Sandbox Code Playgroud)

我有几个问题,这个语法有什么不对,怎么可能将VALUES更改为时间戳而不是字符串的%s?请注意,数据库中的列名称与我脚本中的变量中存储的数据相同.

谢谢

Ama*_*pta 14

试试这个:

import MySQLdb
import time
import datetime

ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
conn = MySQLdb.connect(host= "localhost",
              user="root",
              passwd="newpassword",
              db="db1")
x = conn.cursor()

try:
   x.execute("""INSERT into test (test_date,test1,test2) values(%s,%s,%s)""",(timestamp,test1,test2))
   conn.commit()
except:
   conn.rollback()

conn.close()
Run Code Online (Sandbox Code Playgroud)


Art*_*tem 7

时间戳创建可以在一行中完成,不需要使用time.time(),只需:

from datetime import datetime

timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)