How to store and retrieve a date into MySQL database using Python?

PythonServer Side ProgrammingProgrammingMySQL

To insert a date in a MySQL database, you need to have a column of Type date or datetime in your table. Once you have that, you'll need to convert your date in a string format before inserting it to your 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 will try to insert the tuple (id, date) in your table.

When you fetch a date from a database using a select query, you'll need to parse it back to a datetime object using functions like strptime.

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 created date and parse it to a datetime object.

raja
Published on 08-Jan-2018 14:52:03
Advertisements