首頁  >  文章  >  資料庫  >  如何使用 Python 在 MySQL 資料庫中儲存和檢索日期?

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

PHPz
PHPz轉載
2023-09-14 22:37:02593瀏覽

如何使用 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)插入到您的表中。

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

這將取得建立日期並將其解析為日期時間物件。

以上是如何使用 Python 在 MySQL 資料庫中儲存和檢索日期?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除