开发者

Converting legacy string dates to dates

We have some legacy string dates t开发者_如何学JAVAhat 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?


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)


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:

http://code.activestate.com/recipes/577135-parse-a-datetime-string-to-a-datetime-instance/

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜