In Python there is a certain standard (which is not surprising, of course) for working with dates. For example, if you print datetime.now() , then it will be immediately visible.

So, I want to configure MySQL so that the date can be easily added to the database from Python. What should I specify as an argument of type DATETIME() when creating a table so that everything is correct?

My experience with databases is very small ...

  • What module / library are you using to work with MySQL? - MaxU

1 answer 1

Here is a working example for SQLAlchemy (the de facto standard when working with various databases in Python):

MySQL create table:

 mysql> create table dt( -> id int not null auto_increment primary key, -> dt timestamp default current_timestamp -> ); Query OK, 0 rows affected (0.05 sec) 

Python code:

 import datetime import sqlalchemy db_url = 'mysql://testuser:password@mysql_server_hostname/db_name' engine = sqlalchemy.create_engine(db_url) conn = engine.connect() sql = 'INSERT INTO dt(dt) values(%s)' rslt = conn.execute(sql, (datetime.datetime(2016, 11, 11, 11, 11, 11))) rslt = conn.execute(sql, (datetime.datetime(2016, 12, 12, 12, 12, 12))) conn.close() 

Result:

 mysql> select * from dt; +----+---------------------+ | id | dt | +----+---------------------+ | 1 | 2016-11-11 11:11:11 | | 3 | 2016-12-12 12:12:12 | +----+---------------------+ 2 rows in set (0.00 sec)