在python的mysql表中插入时间戳

ykejflvf  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(381)

bid , best_bid_quantityfloats , 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()

错误-->除非我添加目标日期,否则它将转到

iqjalb3h

iqjalb3h1#

尝试使用 time.strftime() :

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

这个 .timetuple() 方法来转换 datetime.datetime 的对象 target_date 变成一个 time_struct 结构,然后可以在调用 time.strftime .

相关问题