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??

Mazdak
  • 105,000
  • 18
  • 159
  • 188
gis20
  • 1,024
  • 2
  • 15
  • 33

1 Answers1

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)
Mike
  • 6,813
  • 4
  • 29
  • 50
  • 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) – gis20 Jul 06 '15 at 07:29
  • 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. – Mike Jul 06 '15 at 14:26
  • Sure but i am not in the U.S. I am in Europe so my input has dd-mm-yyyy https://en.wikipedia.org/wiki/Date_format_by_country – gis20 Jul 08 '15 at 16:51
  • You may have to create a special case then, I don't think the parse function was meant to work with that format. – Mike Jul 08 '15 at 19:05