从Python中的字符串中提取日期 [英] Extracting date from a string in Python

查看:1045
本文介绍了从Python中的字符串中提取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从猴子2010-07-10爱香蕉字符串中提取日期?谢谢!

解决方案

如果日期是以固定的形式给出的,可以使用正则表达式来提取日期和 datetime.datetime.strptime解析日期:

  match = re.search(r'\d {4}  - \d {2} -\d {2}',text)
date = datetime.strptime(match.group(),'%​​Y-%m-%d')date()

否则,如果日期以任意形式提供,则无法轻松提取。 >

How can I extract the date from a string like "monkey 2010-07-10 love banana"? Thanks!

解决方案

If the date is given in a fixed form, you can simply use a regular expression to extract the date and "datetime.datetime.strptime" to parse the date:

match = re.search(r'\d{4}-\d{2}-\d{2}', text)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()

Otherwise, if the date is given in an arbitrary form, you can't extract it easily.

这篇关于从Python中的字符串中提取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆