要在 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 數據庫中存儲和檢索日期?的詳細內容,更多請關注www.92cms.cn其它相關文章!






