Home > Database > Mysql Tutorial > body text

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

PHPz
Release: 2023-09-14 22:37:02
forward
630 people have browsed it

如何使用 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))
Copy after login

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')
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template