Home  >  Article  >  Database  >  How to store and retrieve dates from a MySQL database using Python?

How to store and retrieve dates from a MySQL database using Python?

PHPz
PHPzforward
2023-09-14 22:37:02593browse

如何使用 Python 在 MySQL 数据库中存储和检索日期?

To insert a date in a MySQL database, your table needs to have a column of type Date or DateTime. Once done, you need to convert the date to string format before inserting it into the database. To do this, you can use the datetime module's strftime formatting function.

Example

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))

Running this command will attempt to insert a tuple (id, date) into your table.

When you use a select query to get a date from the database, you need to use functions such as strptime to parse it back into a datetime object.

Example

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

This will get the creation date and parse it into a datetime object.

The above is the detailed content of How to store and retrieve dates from a MySQL database using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete