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


要在 MySQL 資料庫 中插入日期,表中必須有一列型別為日期或日期時間的列。有了此列後,需要在插入資料庫前將日期轉換為字串格式。可透過使用 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)。

更新於:2023-11-04

16K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.