首页 > 解决方案 > 使用python从日期的左侧和右侧删除字符串

问题描述

string = "I went to market on October 29,2017I"
12-7-2021mma  --->12-7-2021
kk12/7/2021   ---> 12-7-2021
yy12/9/2021kko  ---> 12/9/2021

是否有任何解决方案可以通过从 2017 年 10 月 29 日删除“我”来获得“我于 2017 年 10 月 29 日上市”I

像上面这样的案例还有很多

标签: python-3.x

解决方案


使用dparser

import dateutil.parser as dparser

s = "I went to market on October 29,2017I"
print(dparser.parse(s,fuzzy=True))

输出:

2021-10-29 00:00:00

编辑:

如果您想要特定格式的月份:

s = "I went to market on October 29,2017I"
out = str(dparser.parse(s,fuzzy=True)).split(" ")[0]
print(out)

import datetime
print (datetime.datetime.strptime(out,'%Y-%m-%d').strftime('%B %d, %Y'))

输出:

October 29, 2017

推荐阅读