【问题标题】:Change a buch of dates, regex and python更改一堆日期、正则表达式和 python
【发布时间】:2012-10-17 21:04:21
【问题描述】:

我有一堆格式如下的日期

16th February 2011
4th April 2009
31st December 2007

我想把它们改成这种格式

20110216
20090404
20071231

我想在 python 中执行此操作,我尝试过 regextime,但无法理解它。

【问题讨论】:

  • 通常情况下,我建议使用time.strptime,但那些序数会导致问题。

标签: python regex time python-2.7


【解决方案1】:

您不妨考虑使用parsedatetime 进行模糊日期匹配。

如果您的日期与 NN(ordinal) Month Year 的格式相当不变,则此方法有效:

dates="""\
16th February 2011
4th April 2009
31st December 2007"""

import re
import time

for date in dates.splitlines():
    p=re.findall(r'(\d+)\w\w (\w+) (\d\d\d\d)',date)
    d=time.strptime(' '.join(p[0]),'%d %B %Y')
    iso=time.strftime('%Y%m%d',d)
    print "{0:>20} =>{1:>30} =>{2:>15}".format(date,p,iso)

打印:

  16th February 2011 =>  [('16', 'February', '2011')] =>       20110216
      4th April 2009 =>      [('4', 'April', '2009')] =>       20090404
  31st December 2007 =>  [('31', 'December', '2007')] =>       20071231

【讨论】:

    【解决方案2】:

    分两步完成:

    1. 使用正则表达式(\d+)([a-z]{2})\s+([A-Za-z]+)\s+(\d{4}) 将第二组替换为空字符串

    2. 使用time.strptime(string[, format]) 将日期转换为您需要的格式

    【讨论】:

      【解决方案3】:

      您可以使用正则表达式获取信息,然后使用 strptime 将其转换为日期。

      import datetime
      import re
      date_re = re.compile("^([0-9]+)[a-z]* (.+)$")
      example = "16th February 2011"
      m = date_re.match(example)
      dt = datetime.datetime.strptime("%s %s" % (m.group(1), m.group(2)), "%d %B %Y")
      print dt.strftime("%Y%m%d")
      

      【讨论】:

        【解决方案4】:

        没有导入,用于学习目的。

        months 是月份的字典。

        months = {"January":"01","February":"02",...}    
        # make sure all entries are strings, not integers
        
        for entry in entries:
            # split by spaces.  this is multiple assignment.  
            # the first split gets assigned to date, the second, to month, the third, to year.
            day, month, year = entry.split() 
        
            # parse the date.  the th/rd/nd part is always 2 characters.  
            date = day[:-2]
        
            if len(date) == 1:
                # make sure the date is two characters long
                date = "0" + date 
        
            # concatenate
            print year + months[month] + date 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-16
          • 2012-06-20
          • 1970-01-01
          相关资源
          最近更新 更多