2024-05-20 00:54:57 发布
网友
假设我们有一个字符串:
string = "2014-12-04 04:07:59 <font color='green'> info:</font> One, two, three, four, five."
在Python中,除了2014-12-04,我必须删除所有内容,然后使用
2014-12-04
另一方面,在R中,我所要做的就是as.Date(string),并且我以日期的形式得到适当的日期。Python有这样的东西吗?在
as.Date(string)
如果知道字符串中的位置和日期格式,则可以将切片与strptime一起使用:
strptime
import datetime as dt >>> dt.datetime.strptime(string[:10], '%Y-%m-%d').date() datetime.date(2014, 12, 4)
如果要使用像熊猫这样的软件包:
您还可以使用dateutil包:
from dateutil.parser import parse parse(string[:10]).date() datetime.date(2014, 12, 4)
dateutil的fuzzy参数正是用于此目的:
dateutil
fuzzy
from dateutil.parser import parse string = "2014-12-04 04:07:59 <font color='green'> info:</font> One, two, three, four, five." dt = parse(string, fuzzy=True)
结果是:
如果只需要日期,只需使用dt.date()返回日期对象。在
dt.date()
注意,如果字符串中还有其他可能是日期一部分的内容(例如单词March或其他),这将给解析器带来问题。在
March
如果要查看它跳过的内容,请使用fuzzy_with_tokens:
fuzzy_with_tokens
from dateutil.parser import parse string = "2014-12-04 04:07:59 <font color='green'> info:</font> One, two, three, four, five." dt = parse(string, fuzzy=True) dt, tokens = parse(string, fuzzy_with_tokens=True)
tokens解析为:
tokens
(' ', " <font color='green'> info:</font> One, two, three, four, five.")
要在任意文本中查找日期/时间,可以尝试^{} module:
>>> import parsedatetime as pdt # $ pip install parsedatetime >>> text_with_date = "2014-12-04 04:07:59 <font color='green'> info:</font> One, two, three, four, five." >>> pdt.Calendar().nlp(text_with_date) ((datetime.datetime(2014, 12, 4, 4, 7, 59), 3, 0, 19, '2014-12-04 04:07:59'),)
给定一个datetime对象,调用.date()方法,只获取日期部分。在
datetime
.date()
如果知道字符串中的位置和日期格式,则可以将切片与
strptime
一起使用:如果要使用像熊猫这样的软件包:
^{pr2}$您还可以使用dateutil包:
dateutil
的fuzzy
参数正是用于此目的:结果是:
^{pr2}$如果只需要日期,只需使用
dt.date()
返回日期对象。在注意,如果字符串中还有其他可能是日期一部分的内容(例如单词
March
或其他),这将给解析器带来问题。在如果要查看它跳过的内容,请使用
fuzzy_with_tokens
:tokens
解析为:要在任意文本中查找日期/时间,可以尝试^{} module :
给定一个
datetime
对象,调用.date()
方法,只获取日期部分。在相关问题 更多 >
编程相关推荐