Home  >  Article  >  Database  >  How to Correctly Insert Date and Time Objects into MySQL Using Python?

How to Correctly Insert Date and Time Objects into MySQL Using Python?

DDD
DDDOriginal
2024-11-25 06:39:20144browse

How to Correctly Insert Date and Time Objects into MySQL Using Python?

Type Formatting in MySQL Insertion: Date and Time Objects

When attempting to insert a datetime.datetime object into a MySQL table, one might encounter the error "TypeError: not all arguments converted during string formatting" if using placeholders like %s in the execute statement. This error occurs because MySQL requires specific formatting for date and time values.

To correctly insert a datetime.datetime object, use the following approach:

For time:

import time
time_string = time.strftime('%Y-%m-%d %H:%M:%S')

For date:

import datetime
date_string = datetime.datetime.now().strftime('%Y-%m-%d')

Then, in the execute statement, specify the time/date string as a parameter:

cursor.execute("INSERT INTO table(name, id, datecolumn) VALUES (%s, %s, %s)", ("name", 4, time_string))

Using these formatting methods ensures that the MySQL database can correctly interpret and store the date/time information as intended.

The above is the detailed content of How to Correctly Insert Date and Time Objects into MySQL Using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn