5

I have an unusual date string that I want to insert into a MySQL DB.

date = 'Thu, 14 Mar 2013 13:33:07 -0400'

And here is the insert statement

self.cursor.execute("INSERT INTO table1 (`DATE`)VALUES (%s);",(date))

When I do it like this it shows up in the database like :

0000-00-00 00:00:00

Even if I enter the SQL manualy it shows up the same way.

How do I convert the date string into a mysql readable date for insert?

3 Answers 3

7

pip install python-dateutil

from dateutil.parser import parse
date = 'Thu, 14 Mar 2013 13:33:07 -0400'
parse(date).strftime("%Y-%m-%d %H:%M:%S")
Sign up to request clarification or add additional context in comments.

2 Comments

ImportError: No module named dateutil.parser
pip install python-dateutil
4

This date string is in RFC 2822 date format and can be parsed with email.utils.parsedate (which is part of the standard library):

In [428]: import email.utils as eu

In [429]: eu.parsedate('Thu, 14 Mar 2013 13:33:07 -0400')
Out[429]: (2013, 3, 14, 13, 33, 7, 0, 1, -1)

Once you have a datetime object, you can insert it in that form (without formatting) into MySQL:

date = eu.parsedate('Thu, 14 Mar 2013 13:33:07 -0400')
self.cursor.execute("INSERT INTO table1 (`DATE`) VALUES (%s)",(date,))

Note: The second argument to cursor.execute must be a sequence. So use the tuple (date,) instead of the datetime object (date).

Also, no semicolons are necessary in your SQL strings.

Comments

3

I don't have enough reputation to comment to the question above, so I'll put the answer here.

If you get an ImportError when running this, you need to install the module:

from dateutil.parser import parse

Go here to download the parser: http://labix.org/python-dateutil#head-2f49784d6b27bae60cde1cff6a535663cf87497b

Next, extract the folder and open cmd with admin privileges. Navigate to the folder and type this:

python setup.py install

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.