如何使用 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、日期)。

使用 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')

這將獲取建立日期並將其解析為 datetime 物件。

更新於: 2023 年 9 月 28 日

4 千次+ 瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.