Inserting a Python datetime.datetime object into MySQL

后端 未结 7 1251
Happy的楠姐
Happy的楠姐 2020-11-27 11:26

I have a date column in a MySQL table. I want to insert a datetime.datetime() object into this column. What should I be using in the execute statement?

7条回答
  •  眼角桃花
    2020-11-27 11:48

    What database are you connecting to? I know Oracle can be picky about date formats and likes ISO 8601 format.

    **Note: Oops, I just read you are on MySQL. Just format the date and try it as a separate direct SQL call to test.

    In Python, you can get an ISO date like

    now.isoformat()
    

    For instance, Oracle likes dates like

    insert into x values(99, '31-may-09');
    

    Depending on your database, if it is Oracle you might need to TO_DATE it:

    insert into x
    values(99, to_date('2009/05/31:12:00:00AM', 'yyyy/mm/dd:hh:mi:ssam'));
    

    The general usage of TO_DATE is:

    TO_DATE(, '')
    

    If using another database (I saw the cursor and thought Oracle; I could be wrong) then check their date format tools. For MySQL it is DATE_FORMAT() and SQL Server it is CONVERT.

    Also using a tool like SQLAlchemy will remove differences like these and make your life easy.

提交回复
热议问题