Inserting a Python datetime.datetime object into MySQL

后端 未结 7 1196
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:31

    If you're just using a python datetime.date (not a full datetime.datetime), just cast the date as a string. This is very simple and works for me (mysql, python 2.7, Ubuntu). The column published_date is a MySQL date field, the python variable publish_date is datetime.date.

    # make the record for the passed link info
    sql_stmt = "INSERT INTO snippet_links (" + \
        "link_headline, link_url, published_date, author, source, coco_id, link_id)" + \
        "VALUES(%s, %s, %s, %s, %s, %s, %s) ;"
    
    sql_data = ( title, link, str(publish_date), \
                 author, posted_by, \
                 str(coco_id), str(link_id) )
    
    try:
        dbc.execute(sql_stmt, sql_data )
    except Exception, e:
        ...
    
    0 讨论(0)
  • 2020-11-27 11:37

    For a time field, use:

    import time    
    time.strftime('%Y-%m-%d %H:%M:%S')
    

    I think strftime also applies to datetime.

    0 讨论(0)
  • 2020-11-27 11:40

    when iserting into t-sql

    this fails:

    select CONVERT(datetime,'2019-09-13 09:04:35.823312',21)
    

    this works:

    select CONVERT(datetime,'2019-09-13 09:04:35.823',21)
    

    easy way:

    regexp = re.compile(r'\.(\d{6})')
    def to_splunk_iso(dt):
        """Converts the datetime object to Splunk isoformat string."""
        # 6-digits string.
        microseconds = regexp.search(dt).group(1)
        return regexp.sub('.%d' % round(float(microseconds) / 1000), dt)
    
    0 讨论(0)
  • 2020-11-27 11:45

    You are most likely getting the TypeError because you need quotes around the datecolumn value.

    Try:

    now = datetime.datetime(2009, 5, 5)
    
    cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
                   ("name", 4, now))
    

    With regards to the format, I had success with the above command (which includes the milliseconds) and with:

    now.strftime('%Y-%m-%d %H:%M:%S')
    

    Hope this helps.

    0 讨论(0)
  • 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(<string>, '<format>')
    

    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.

    0 讨论(0)
  • 2020-11-27 11:51

    Try using now.date() to get a Date object rather than a DateTime.

    If that doesn't work, then converting that to a string should work:

    now = datetime.datetime(2009,5,5)
    str_now = now.date().isoformat()
    cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now))
    
    0 讨论(0)
提交回复
热议问题