
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Insert Date Object in MySQL Using Python
When working with databases, especially MySQL, handling dates correctly is crucial. Python's datetime module provides powerful tools for managing dates and times. To insert a date into a MySQL database, which has a column of DATE or DATETIME type. Following are several methods to achieve this.
- Using strftime() for Formatting
- Using isoformat() Method
- Passing datetime object directly to the connector
Using 'strftime()' for Formatting
The strftime() method allows you to format a datetime object into a string according to a specific format. The '%Y', '%m', '%d', '%H', '%M', and '%S' directives are placeholders that strftime() replaces with the corresponding year, month, day, hour, minute, and second from your `datetime` object.
Example
The following example, demonstrates the usage of strftime() to format a datetime object into a string. Here, strftime('%Y-%m-%d %H:%M:%S') is used where '%Y' is the year with century, `%m` is the month, `%d' is the day, '%H' is the hour, '%M' is the minute, and '%S' is the second.
from datetime import datetime import mysql.connector # Database connection details mydb = mysql.connector.connect( host="your_host", user="your_user", password="your_password", database="your_database" ) mycursor = mydb.cursor() # Get the current date and time now = datetime.now() id_value = 1 # Format the datetime object into a string formatted_date = now.strftime('%Y-%m-%d %H:%M:%S') # SQL query to insert data sql = "INSERT INTO your_table (id, date_created) VALUES (%s, %s)" val = (id_value, formatted_date) mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.")
Following is the output of the above code ?
1 record inserted.
Using 'isoformat()' Method
The isoformat() method offers a more specified way to convert a 'datetime' object into a string. Instead of manually specifying the format with directives like strftime(), isoformat() automatically produces a string that adheres to the ISO 8601 standard. This standard defines an unambiguous way to represent dates and times, making it ideal for data exchange and storage.
The resulting string looks like `YYYY-MM-DDTHH:MM:SS.ffffff`, where `T` separates the date and time, and 'ffffff' represents microseconds.
Example
This method is very similar to the first one, but instead of using strftime(), we use isoformat() to format the date. The isoformat() method produces a string in the format 'YYYY-MM-DDTHH:MM:SS.ffffff', which is generally compatible with MySQL's 'DATETIME' type.
from datetime import datetime import mysql.connector # Database connection details (replace with your actual credentials) mydb = mysql.connector.connect( host="your_host", user="your_user", password="your_password", database="your_database" ) mycursor = mydb.cursor() # Get the current date and time now = datetime.now() id_value = 2 # Format the datetime object into an ISO format string formatted_date = now.isoformat() # SQL query to insert data sql = "INSERT INTO your_table (id, date_created) VALUES (%s, %s)" val = (id_value, formatted_date) # Execute the query mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.")
Following is the output of the above code ?
1 record inserted.
Passing datetime object directly to the connector
Connectors provides the capability to manage datetime objects. This built-in functionality rectifies the necessity for developers to manually format these objects before inserting them into the database or retrieving them. Instead of requiring explicit formatting steps, these connectors can intelligently interpret and process datetime objects directly.
Example
In this example, we directly pass the 'datetime' object 'now' to the 'execute()' method. The MySQL connector might automatically convert this Python 'datetime' object into a format that MySQL understands.
from datetime import datetime import mysql.connector # Database connection details mydb = mysql.connector.connect( host="your_host", user="your_user", password="your_password", database="your_database" ) mycursor = mydb.cursor() # Get the current date and time now = datetime.now() id_value = 3 # SQL query to insert data sql = "INSERT INTO your_table (id, date_created) VALUES (%s, %s)" val = (id_value, now) # Pass the datetime object directly # Execute the query mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.")
Following is the output of the above code ?
1 record inserted.