Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Insert Date Object ลง MySQL ด้วย Python

เพื่อ Insert Date ลง MySQL ต้องมี Column Type DATE หรือ DATETIME ใน Table แปลง Date เป็น String Format ก่อน Insert ใช้ strftime ของ datetime Module

ตัวอย่าง

from datetime import datetime

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

# สมมติมี cursor
cursor.execute('INSERT INTO table(id, date_created) VALUES(%s, %s)', (id, formatted_date))

รันคำสั่งนี้จะ Insert Tuple (id, date) ลง Table