如何在 Python 中在 MySQL 中插入日期物件?


要在 MySQL 資料庫 中插入日期,表中需要有一列型別為 date 或 datetime。有了它之後,你需要在插入到資料庫之前將日期轉換成字串格式。為此,可以使用 datetime 模組的 strftime() 格式化函式

例如

from datetime import datetime
now = datetime.now()
id = 1
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# Assuming you have a cursor named cursor you want to execute this query on:
cursor.execute('insert into table(id, date_created) values(%s, %s)', (id, formatted_date))

執行此程式碼將嘗試在表中插入元組 (id, date)。

更新於: 04-11-2023

16K+ 次瀏覽

職業起步

透過完成課程來獲得認證

開始學習
廣告
© . All rights reserved.