2011-04-10 78 views
1

从Python网站获取日期字符串的最佳方式是什么?使用Python获取日期字符串的最佳方式

的datestrings可以是,例如,在的形式:

  • 2011年4月1日
  • 2011年4月2日
  • 2011年4月23日
  • 2011年4月2日
  • 04/23/2011

这将不得不是一吨的正则表达式吗?什么是最优雅的解决方案?

+1

是的,这是一个模式匹配问题。 – euphoria83 2011-04-10 05:30:11

+0

可能的重复[是否有任何python库从自然语言解析日期和时间?](http://stackoverflow.com/questions/1495487/is-there-any-python-library-for-parsing-dates-和自然语言的时间) – 2011-04-10 05:41:36

+0

你只在寻找英文月份名称吗? – 2011-04-10 10:04:02

回答

2

考虑这个LIB:http://code.google.com/p/parsedatetime/

从它的例子Wiki页面,这里有一对夫妇的格式,它可以处理,看起来有关你的问题:

result = p.parseDateText("March 5th, 1980") 
result = p.parseDate("4/4/80") 

编辑:现在我发现它实际上是一个this SO question的副本,建议使用相同的库!

+0

我结束了使用六个正则表达式字符串来找到最常见的日期格式,但我会给你答案 – Lionel 2011-10-03 02:29:00

1
month = '(jan|feb|mar|apr|may|jun|jul|aug|sep|nov|dec)[a-z]{0,6}' 
    regex_strings = ['%s(\.|)\d{1,2},? \d{2,4}' % month, # Month.Day, Year 
        '\d{1,2} %s,? \d{4}' % month, # Day Month Year(4) 
        '%s \d{1,2}\w{2},? \d{4}' % month, # Mon Day(th), Year 
        '\d{1,2} %s' % month, # Day Month 
        '\d{1,2}\.\d{1,2}\.\d{4}', # Month.Day.Year 
        '\d{1,2}/\d{1,2}/\d{2,4}', # Month/Day/Year{2,4} 
        ] 
相关问题