Mysql – Converting Python’s date format to a MySQL

date formatMySQL

First of all I hope this is the right place to ask.
I have a Python script which parses data from a few links. In the parsers I parse also the date of the last modified article.

This is the output of the date in the code;

2012-08-07T09:00:00 # Year, month, day, hour, minute, seconds

I have to throw this output to a Mysql database with the type DATETIME
When I throw this to the database, I check the field later on, I only have;

0000-00-00 00:00:00

(Although I am using SQLALchemy, it gives me the warning when inserting to the table);

/usr/lib/python2.7/site-packages/sqlalchemy/engine/default.py:331: Warning: Out of range value for column 'cdate' at row 1
  cursor.execute(statement, parameters)
/usr/lib/python2.7/site-packages/sqlalchemy/engine/default.py:331: Warning: Out of range value for column 'mdate' at row 1
  cursor.execute(statement, parameters)

Well, clear enough I am not putting the right content inside, so I wonder if there is any converter in Mysql or you know something in Python that will work this out for me.
I guess formating the whole string will be a bit of a pain and "useless" if there is something like that already.

Cheers.
– Ephexeve

Best Answer

I found a solution for this.

As you can see the time format is;

2012-08-07T09:00:00

I could easily strip the "t" but that wouldn't work and could(?) give me some trouble. I found out that the lib I was using (feedparser) could also return me a Python time object, looking like this:

time.struct_time(tm_year=2012, tm_mon=8, tm_mday=7, tm_hour=19, tm_min=0, tm_sec=22, tm_wday=1, tm_yday=220, tm_isdst=0)

Basicly.. a time.struct_time type. With an example, you can see what I have done (examples made with iPython)

In [83]: date
Out[83]: time.struct_time(tm_year=2012, tm_mon=8, tm_mday=7, tm_hour=15,tm_min=51, tm_sec=19, tm_wday=1, tm_yday=220, tm_isdst=0)
In [84]: date = datetime.datetime(*date[:-3]).strftime("%Y-%m-%d %H:%M:%S")

In [85]: date
Out[85]: '2012-08-07 15:51:19'

Voila!