
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to store and retrieve a date into MySQL database using Python?
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.
- Related Articles
- How to store and retrieve date into Sqlite3 database using Python?
- How do we insert/store a file into MySQL database using JDBC?
- How to insert/store JSON array into a database using JDBC?
- Write a query to store and retrieve book information in the database (DBMS)?
- What is the easiest way to store date in MySQL database?
- How to get the id after INSERT into MySQL database using Python?
- How to store usernames and passwords safely in MySQL database?
- How to retrieve table names from a database in MySQL?
- How to insert DATE into a MySQL column value using Java?
- Store and retrieve arrays into and from HTML5 data attributes with jQuery?
- How to correctly convert a date format into a MySQL date?
- Where does MySQL store database files?
- How to insert DECIMAL into MySQL database?
- How to read/retrieve data from Database to JSON using JDBC?
- How to insert current date and time in a database using JDBC?

Advertisements