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

PHPz
發布: 2023-09-14 22:37:02
轉載
487 人瀏覽過

如何使用 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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!