Create a parsing function for different date formats in Python
I want to create a parsing function with lambda capable of recognizing 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 values missing in the clock
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 wrong
Any idea?
+3
source to share
1 answer
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-isolated formats such as
>>> dateutil.parser.parse('5-6-15')
datetime.datetime(2015, 5, 6, 0, 0)
+2
source to share