【问题标题】:Best way to get date strings with Python使用 Python 获取日期字符串的最佳方法
【发布时间】:2011-04-10 05:25:41
【问题描述】:

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

日期字符串可以采用以下形式,例如:

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

这必须是大量的正则表达式吗?最优雅的解决方案是什么?

【问题讨论】:

标签: python regex parsing date


【解决方案1】:

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

在其示例 Wiki 页面中,它可以处理与您的问题相关的几种格式:

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

编辑:现在我注意到它实际上是 this SO question 的副本,其中推荐了同一个库!

【讨论】:

  • 我最终使用了六个正则表达式字符串来查找最常见的日期格式,但我会给你答案
【解决方案2】:
    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}
                     ]

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2016-11-23
    • 2013-05-15
    • 2012-11-25
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2020-07-10
    相关资源
    最近更新 更多