0

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?

2 Answers 2

1

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".

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! Just want to confirm something: Why would May 2014 be parsed as having the 6th as the date?
0

You might also want to checkout dateparser:

>>> import dateparser
>>> dates = ['August 2, 2008', '04-02-2007', 'May 2014']
>>> [dateparser.parse(d, settings={'PREFER_DAY_OF_MONTH': 'first'}).strftime('%Y-%m-%d') for d in dates]
['2008-08-02', '2007-04-02', '2014-05-01']

Plus side is you can specify to fill date with day missing (e.g. May 2014) to use either first day of the month, last or current.

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.