We have some legacy string dates that I need to convert to actual dates that can be used to perform some date logic. Converting to a date object isn't a problem if I knew what the format were! That is, some people wrote 'dd month yy', othes 'mon d, yyyy', etc.

So, I was wondering if anybody knew of a py module that attempts to guess date formats and rewrites them in a uniform way?

Any other suggestions?

Thanks! :)


2 Answers

Brian Clapper On Best Solutions

The typical approach is to define a list of formats (strptime formats, specifically), and try them in turn, until one works. As an example, see this recipe:


strptime accepts quite a number of formats. If you can enumerate all the possibilities you'll see, you should be able to hack together a variant of that recipe that'll do what you want.

unutbu On

Using dateutil:

In [25]: import dateutil.parser as parser

In [26]: parser.parse('25 December 2010')
Out[26]: datetime.datetime(2010, 12, 25, 0, 0)

In [27]: parser.parse('Dec 25, 2010')
Out[27]: datetime.datetime(2010, 12, 25, 0, 0)