首页 文章

python正则表达式,日期格式[关闭]

提问于
浏览
-8

我需要在python中使用日期格式的正则表达式

我想要“3月29日”

但不是“3月29日”,“3月29日,YYYY”,YYYY不是2012年

谢谢,

5 回答

  • 2

    听起来像这样:

    re.compile(r'''^
       (january|february|march|...etc.)
       \s
       \d{1,2}
       \s
       (,\s2012)?
       $''', re.I)
    
  • 1

    我自己想通了

    (?!\ S * \ S *(1 \ d \ d \ d | 200 \ d | 2010 | 2011))

  • 1

    获得月和日的原始正则表达式是: (january|february|...) \d\d?(?!\s*,\s*\d{4}) .

    (?!\s*,\s*\d{4}) 向前看并确保字符串后面没有 , YYYY . 我希望我理解你的这部分问题 . 它将不匹配 march 29, 2012 因为3月29日之后是逗号空间年 .

  • 0

    您不需要使用正则表达式 .

    import datetime
    
    dt = datetime.datetime.now()
    print dt.strftime('%B %d')
    

    结果将是:

    June 18
    

    顺便说一句,如果你想对日期列表进行排序并仅显示2012年的日期,而不是尝试使用 split()

    line = "March 29, YYYY"
    if int(line.split(',')[1]) = 2012
        print line
    else
        pass
    
  • 0

    您的问题不是100%明确,但看起来您正在尝试从传入的字符串中解析日期 . 如果是这样,请使用datetime module而不是正则表达式 . 它更有可能处理语言环境等 . datetime.datetime.strptime() 方法旨在从字符串中读取日期,因此请尝试以下操作:

    import datetime
    
    def myDate(raw):
        # Try to match a date with a year.
        try:
            dt = datetime.datetime.strptime(raw, '%B %d, %Y')
    
            # Make sure its the year we want.
            if dt.year != 2012:
                return None
    
        # Error, try to match without a year.
        except ValueError:
            try:
                dt = datetime.datetime.strptime(raw, '%B %d')
            except ValueError:
                return None
    
            # Add in the year information - by default it says 1900 since
            # there was no year details in the string.
            dt = dt.replace(year=2012)
    
        # Strip away the time information and return just the date information.
        return dt.date()
    

    strptime() 方法返回 datetime 对象,即日期和时间信息 . 因此,最后一行调用 date() 方法只返回日期 . 另请注意,当没有有效输入时,该函数返回 None - 您可以轻松地将其更改为执行您所需的任何操作 . 有关不同格式代码的详细信息,请参阅the documentation of the strptime() method .

    一些使用示例:

    >>> myDate('March 29, 2012')
    datetime.date(2012, 3, 29)
    >>> myDate('March 29, 2011')
    >>> myDate('March 29, 2011') is None
    True
    >>> myDate('March 29')
    datetime.date(2012, 3, 29)
    >>> myDate('March 39')
    >>> myDate('March 39') is None
    True
    

    你会注意到这个捕获并拒绝接受非法日期(例如,3月39日),这可能是一个难以处理的正则表达式 .

相关问题