添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

python-mysql How do I insert the current datetime into a MySQL database using Python?


Using Python, you can insert the current datetime into a MySQL database by first creating a datetime object and then using the cursor.execute() method. The following example code block shows how to do this:

import mysql.connector
from datetime import datetime
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address, date_time) VALUES (%s, %s, %s)"
val = ("John", "Highway 21", datetime.now())
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

Output example

1 record inserted.

The code can be broken down into the following parts:

  • Import the mysql.connector and datetime modules.
  • Connect to the MySQL database.
  • Create a datetime object.
  • Create an SQL query with placeholders for the values.
  • Execute the query with the datetime object as one of the values.
  • Commit the changes to the database.
  • Print the number of records inserted.
  •