如何解析包含“ st”,“ nd”,“ rd”或“ th”的日期日期?
问题内容:
我有这样的字符串
"1st January 2014"
我想将其解析为datetime.date
。我可以做这个:
如果日期是1 January 2014
我做的:replace(' ','')
那么datetime.strptime(SecondDateString, "%d%B%Y").date()
但是,这不工作的时候,天有st
,nd
,rd
,或th
。
编辑:
你可能会说,我自己删除st
,nd
,rd
,或th
再使用上面我自己的方式,是的,这是一个解决方案,但我要问,如果蟒蛇已经有我的东西。
问题答案:
您可以使用regex
来代替st
,nd
,rd
,th
用一个空字符串:
import re
def solve(s):
return re.sub(r'(\d)(st|nd|rd|th)', r'\1', s)
演示:
>>> datetime.strptime(solve('1st January 2014'), "%d %B %Y")
datetime.datetime(2014, 1, 1, 0, 0)
>>> datetime.strptime(solve('3rd March 2014'), "%d %B %Y")
datetime.datetime(2014, 3, 3, 0, 0)
>>> datetime.strptime(solve('2nd June 2014'), "%d %B %Y")
datetime.datetime(2014, 6, 2, 0, 0)
>>> datetime.strptime(solve('1st August 2014'), "%d %B %Y")
datetime.datetime(2014, 8, 1, 0, 0)