เพื่อเพิ่มวันที่ในฐานข้อมูล MySQL คุณต้องมีคอลัมน์ประเภท date หรือ datetime ในตาราง ก่อนอื่นต้องแปลงวันที่เป็นรูปแบบสตริงก่อนเพิ่มเข้าไป สามารถใช้ฟังก์ชัน strftime ของโมดูล datetime
ตัวอย่างการ Insert วันที่
from datetime import datetime
now = datetime.now()
id = 1
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# สมมติว่ามี cursor ชื่อ cursor
cursor.execute('insert into table(id, date_created) values(%s, %s)', (id, formatted_date))
การรันคำสั่งนี้จะพยายามเพิ่ม tuple (id, date) ลงในตาราง
ตัวอย่างการดึงและแปลงวันที่
from datetime import datetime
# สมมติว่ามี cursor ชื่อ cursor
cursor.execute('select id, date_created from table where id=1')
# ดึงข้อมูลกลับมา
id, date_str = cursor.fetchone()
# วันที่ถูกส่งคืนเป็นสตริงในรูปแบบที่เราส่งไป ต้องแปลงกลับด้วย strptime
created_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
โค้ดนี้จะดึงวันที่สร้างและแปลงเป็นออบเจ็กต์ datetime