0

I have strings like this:

3/11/2014
3 January 2014
3rd 11 2014
3th January 2014

Is there any posiblity that I can make a date variable from those strings?

I know that

i can make a date variable from string with format like this:

datetime.strptime("3-11-2014","%d-%m-%Y").date()

my problem

the format of the date is unknown

so onetime it is 3/11/2014, another time it is 3-11-2014, another time it is 3th janary 2014

Alok
  • 2,629
  • 4
  • 28
  • 40
Marco Dinatsoli
  • 10,322
  • 37
  • 139
  • 253

1 Answers1

3

Use dateutil's parse function:

In [217]:

dates=['3/11/2014',
'3 January 2014',
'3rd 11 2014',
'3th January 2014']

import dateutil as dt
In [218]:

for date in dates:
    print(dt.parser.parse(date))
2014-03-11 00:00:00
2014-01-03 00:00:00
2014-03-11 00:00:00
2014-01-03 00:00:00

For the situation where you know the year or day is first you can set param yearfirst=True and dayfirst=True, this assumes that this convention is maintained throughout, if not then it is impossible to disambiguate the dates.

EdChum
  • 376,765
  • 198
  • 813
  • 562
  • i have just one input, not list of inputs, also, what is `in[217` ? – Marco Dinatsoli Mar 07 '14 at 09:36
  • there is not model called "dateutil" – Marco Dinatsoli Mar 07 '14 at 09:37
  • My code is just an example, the `in[217]` is IPython output, ignore it, it is not python code as such. The point being that dateutils's `parse` method should handle most cases – EdChum Mar 07 '14 at 09:38
  • You need to install it, if you have pip installed then this is simply `pip install python-dateutil` from your command line also there are other methods see related: http://stackoverflow.com/questions/11962714/installing-python-dateutil – EdChum Mar 07 '14 at 09:39
  • now I am able to import `dateutil` but i got this error `parser` is not existed – Marco Dinatsoli Mar 09 '14 at 14:29
  • @MarcoDinatsoli are you importing the same as my code or as `import dateutil` rather than `import dateutil as dt`? If the former then you would need to do `dateutil.parser.parse` – EdChum Mar 09 '14 at 17:01