简体   繁体   English

使用日期时间从字符串中提取预期日期

[英]Extract expected Date from String by using datetime

String:- "Today is November 19th, 2019."字符串:- “今天是 2019 年 11 月 19 日。”

Output:- November 19th, 2019 Output:- 2019 年 11 月 19 日

I tried this:-我试过这个: -

datetime.strptime(re.search((January|February|March|April|May|June|July|August|September|Octomber|November|December) \d{1,2}(th|st|rd), \d{4}",String).group(), "%B %d, %Y")

But it shows me Error like:-但它向我显示了如下错误:-

ValueError: time data 'November 11th, 2019' does not match format '%B %d(th|st|rd), %Y' ValueError:时间数据“2019 年 11 月 11 日”与格式“%B %d(th|st|rd), %Y”不匹配

Can anyone help me in this, Where I am wrong.任何人都可以帮助我,我错了。

The datetime formatting does not support regex-like patterns, so you should build a string of a fixed format first for it parse. datetime时间格式不支持类似正则表达式的模式,因此您应该首先构建一个固定格式的字符串以对其进行解析。

You can use re.sub instead to extract only the month, day and year from the string and reassemble them into a space-delimited string before passing to datetime.strptime for parsing:您可以改用re.sub从字符串中仅提取月、日和年,并将它们重新组合成以空格分隔的字符串,然后datetime.strptime进行解析:

datetime.strptime(re.sub(r'.*\b(January|February|March|April|May|June|July|August|September|Octomber|November|December) (\d{1,2})(?:th|st|rd), (\d{4})\b.*', r'\1 \2 \3', String), "%B %d %Y")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM