3

I want to create a parse function with lambda able to recognize two different formats

"2014-01-06 15:23:00"

and

"2014-01-06"

The idea is to use this function to create a pandas dataframe but in some of the values the hour is missing

This is my first idea

parse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') if x is True else pd.datetime.strptime(x, '%Y-%m-%d')

it seems that x is True is not correct

Any idea??

2
  • You could do … if len(x) > 10 else … Commented Jul 4, 2015 at 14:52
  • 2
    As an advise,since you need to handle some exceptions and errors in your function i think lambda is not a correct choice for this task! and so when you use a def all the ties will be open! Commented Jul 4, 2015 at 14:52

1 Answer 1

2

dateutil has a parser that handles multiple formats:

>>> dateutil.parser.parse('2015-07-04')
datetime.datetime(2015, 7, 4, 0, 0)

>>> dateutil.parser.parse('2015-07-04 11:23:00')
datetime.datetime(2015, 7, 4, 11, 23)

>>> dateutil.parser.parse('2015-07-04T11:23:56')
datetime.datetime(2015, 7, 4, 11, 23, 56)

Even non iso formats like this

>>> dateutil.parser.parse('5-6-15')
datetime.datetime(2015, 5, 6, 0, 0)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Mike. Yes I know but with dd-mm-yy format does not produce the right ouput result. In your example ('5-6-15') gives datetime.datetime(2015, 5, 6, 0, 0) instead of (2015, 6, 5, 0, 0)
dd-mm-yy is not typically the way dates are written (at least not in the U.S.) Generally if you put the year at the end its month-day-year.
Sure but i am not in the U.S. I am in Europe so my input has dd-mm-yyyy en.wikipedia.org/wiki/Date_format_by_country
You may have to create a special case then, I don't think the parse function was meant to work with that format.

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.