在python的mysql表中插入时间戳

时间:2018-07-04 12:51:08

标签: python mysql

bidbest_bid_quantityfloatstarget_date在我的数据库中设置为timestamp

获取时间戳

target_date_time_ms = (k.lastRestRequestTimestamp) 

base_datetime = datetime.datetime( 1970, 1, 1 )

delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )

target_date = base_datetime + delta

timestamp = target_date

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                         user="root",         # your username
                         passwd="lolilol",  # your password
                         db="test")        # name of the data base

cur = db.cursor()

try:

   cur.execute("""INSERT INTO test1 (heure, prix, quantite) VALUES ({},{},{})""".format(target_date, bid, best_bid_quantity))
   db.commit()

except:
    print('did not insert')
    db.rollback()

db.close()

错误->除非我添加了target_date,否则就去了

1 个答案:

答案 0 :(得分:1)

尝试使用time.strftime()

time.strftime('%Y-%m-%d %H:%M:%S', target_date.timetuple())

需要使用.timetuple()方法将datetime.datetime的{​​{1}}对象转换为target_date结构,然后可以将其用于对time_struct的调用中