0

I have some strings which come to me in formats like

29-Jul-2014 or 03-Aug-2015

What is the easiest way to convert this to a datetime.date object?

I can only think to make a dictionary like d = {'Jul': 7, 'Aug': 8, ...} and then do

dt = datetime.date(year, d[month], day)

Is there any other easier way and avoid the creation of this dictionary?

Thanks

2 Answers 2

3

Use datetime.datetime.strptime to convert the string to datetime.datetime object.

>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y')
datetime.datetime(2014, 7, 29, 0, 0)

Then, use datetime.datetime.date method to convert it to datetime.date object:

>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y').date()
datetime.date(2014, 7, 29)
Sign up to request clarification or add additional context in comments.

Comments

0

The easy way is use dateutil.parse module, it lets to parse the common date formats, even if you don't know what it is using currently
Ex:

>>> import dateutil.parser
>>> 
>>> utc_time     = '2014-07-29T00:00:00'
>>> verbose_time = '29-Jul-2014'
>>> some_locale  = '29/7/14'
>>> dateutil.parser.parse(utc_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(verbose_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(some_locale)
datetime.datetime(2014, 7, 29, 0, 0)

Once you have a datetime object, you only should invoke the datetime.date() method

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.