2011-04-10 54 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} 
        ] 
相關問題