我有一根这样的绳子
"1st January 2014"
我想把它解析成一个
datetime.date
。我可以做到:如果日期
1 January 2014
我做这个:
replace(' ','')
然后datetime.strptime(SecondDateString, "%d%B%Y").date()
但当一天有
st
、nd
、rd
或th
时,这就不起作用。编辑:
你可能会说我自己删除了
st
、nd
、rd
或th
,然后使用上面我自己的方法,是的,这是一个解决方案,但我问python是否已经为我准备了一些东西。 最佳答案
您可以使用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)