Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Insert date object vào MySQL dùng Python

Để insert date vào MySQL, cần column type DATE hoặc DATETIME. Convert date thành string format trước khi insert. Dùng strftime của datetime module.

Ví dụ

from datetime import datetime

now = datetime.now()
id = 1
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')

# Giả sử có cursor
cursor.execute(
    'INSERT INTO table (id, date_created) VALUES (%s, %s)',
    (id, formatted_date)
)

Lưu ý: MySQL DATETIME format: YYYY-MM-DD HH:MM:SS. Dùng parameterized query (%s) để tránh SQL injection.