首页 > 解决方案 > 在python中的mysql表中插入时间戳

问题描述

bid, best_bid_quantityare floats,target_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

时间戳 = 目标日期

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

标签: pythonmysql

解决方案


尝试使用time.strftime()

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

.timetuple()方法需要将 的datetime.datetime对象target_date转换为time_struct结构,然后可以在对 的调用中使用该结构time.strftime


推荐阅读