

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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?
- Store and retrieve arrays into and from HTML5 data attributes with jQuery?
- How to store usernames and passwords safely in MySQL database?
- How to retrieve table names from a database in MySQL?
- How to get the id after INSERT into MySQL database using Python?
- How to correctly convert a date format into a MySQL date?
- How to insert DATE into a MySQL column value using Java?
- Where does MySQL store database files?
- How to insert DECIMAL into MySQL database?
- Creating and Using a MySQL Database
- How to insert current date and time in a database using JDBC?
Advertisements