【发布时间】:2012-06-20 00:29:00
【问题描述】:
我需要一个用于 python 中日期格式的正则表达式
我想要“3 月 29 日”
但不是“March 29, YYYY”中的“March 29”,其中 YYYY 不是 2012 年
谢谢,
程
【问题讨论】:
我需要一个用于 python 中日期格式的正则表达式
我想要“3 月 29 日”
但不是“March 29, YYYY”中的“March 29”,其中 YYYY 不是 2012 年
谢谢,
程
【问题讨论】:
听起来像这样:
re.compile(r'''^
(january|february|march|...etc.)
\s
\d{1,2}
\s
(,\s2012)?
$''', re.I)
【讨论】:
获取月份和日期的原始正则表达式是:(january|february|...) \d\d?(?!\s*,\s*\d{4})。
(?!\s*,\s*\d{4}) 向前看并确保字符串后面没有, YYYY。我希望我理解你问题的这一部分。它不会匹配 march 29, 2012,因为 3 月 29 日后面是逗号空格年份。
【讨论】:
2012,只是没有其他年份。
你不需要使用正则表达式。
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
【讨论】:
我自己想出来的
(?!\s*,\s*(1\d\d\d|200\d|2010|2011))
【讨论】:
您的问题不是 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 日),这可能很难用正则表达式处理。
【讨论】: