user2827048 user2827048 - 3 months ago 12
MySQL Question

Is there a way to convert multiple date formats into datetime python

Is there an easy way to convert multiple date formats into a datetime object in python? Eventually these will be inserted into a MySQL database with type DATE.

Examples of what type of data I might be receiving:

August 2, 2008

04-02-2007

May 2014

Converted I would like these to be:

2008-08-02

2007-04-02

2014-05-00

Is there a simple way to do this or do I have to hard code each scenario?

Answer

Use the third party dateutil library:

>>> from dateutil import parser
>>> parser.parse("August 2, 2008")
datetime.datetime(2008, 8, 2, 0, 0)
>>> parser.parse("04-02-2007")
datetime.datetime(2007, 4, 2, 0, 0)
>>> parser.parse("May 2014")
datetime.datetime(2014, 5, 6, 0, 0)

Converting to required format:

>>> parser.parse("August 2, 2008").strftime('%Y-%m-%d')
'2008-08-02'
>>> parser.parse("04-02-2007").strftime('%Y-%m-%d')
'2007-04-02'
>>> parser.parse("May 2014").strftime('%Y-%m-%d')
'2014-05-06'

You can install it with pip:

pip install python-dateutil

Also look at:

>>> parser.parse("May 2014")
datetime.datetime(2014, 5, 6, 0, 0)
>>> # As you wanted day to be 0 and that is not valid
...
>>> datetime.datetime(2014, 5, 0, 0, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
>>> # Workaround:
...
>>> from datetime import datetime
>>> datedefault = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
>>> parser.parse("May 2014",default=datedefault).strftime('%Y-%m-%d')
'2014-05-01'

If day is not specified in the date string and also no default is specified, it will take the current day. Since today is 06 Aug 2016, it replaced the day to 0 in the first section of the answer for "May 2014".

Comments