如何使用 Python 將日期儲存和檢索到 MySQL 資料庫中?


要在 MySQL 資料庫中插入一個日期,需要在表中有一個 Type 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)。

使用 select 查詢從資料庫中獲取日期時,你需要使用 strptime 等函式將其解析回 datetime 物件。

示例

from datetime import datetime
# Assuming you have a cursor named cursor you want to execute this query on:
cursor.execute('select id, date_created from table where id=1')
# if you inserted the row above, you can get it back like this
id, date_str = cursor.fetchone()
# date is returned as a string in format we sent it as. So parse it using strptime
created_date = datetime.strptime(date_created, '%Y-%m-%d %H:%M:%S')

這將獲取 created date 並將其解析為 datetime 物件。

更新於: 2023-09-28

4K+ 瀏覽量

啟動你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.