Inserting a Python datetime.datetime object into MySQL

后端 未结 7 1197
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:58

    Use Python method datetime.strftime(format), where format = '%Y-%m-%d %H:%M:%S'.

    import datetime
    
    now = datetime.datetime.utcnow()
    
    cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, %s)",
                   ("name", 4, now.strftime('%Y-%m-%d %H:%M:%S')))
    

    Timezones

    If timezones are a concern, the MySQL timezone can be set for UTC as follows:

    cursor.execute("SET time_zone = '+00:00'")
    

    And the timezone can be set in Python:

    now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
    

    MySQL Documentation

    MySQL recognizes DATETIME and TIMESTAMP values in these formats:

    As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012@12@31 11^30^45' are equivalent.

    The only delimiter recognized between a date and time part and a fractional seconds part is the decimal point.

    The date and time parts can be separated by T rather than a space. For example, '2012-12-31 11:30:45' '2012-12-31T11:30:45' are equivalent.

    As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date. For example, '20070523091528' and '070523091528' are interpreted as '2007-05-23 09:15:28', but '071122129015' is illegal (it has a nonsensical minute part) and becomes '0000-00-00 00:00:00'.

    As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.

    0 讨论(0)
提交回复
热议问题