Skip to content Skip to sidebar Skip to footer

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 typ

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

Post a Comment for "Is There A Way To Convert Multiple Date Formats Into Datetime Python"