Home > Database > Mysql Tutorial > 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
Release: 2024-11-25 06:39:20
Original
173 people have browsed it

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')
Copy after login

For date:

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

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))
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template