有没有as.日期在Python(R)中等价?

2024-05-20 00:54:57 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有一个字符串:

string = "2014-12-04 04:07:59 <font color='green'> info:</font> One, two, three, four, five."

在Python中,除了2014-12-04,我必须删除所有内容,然后使用

^{pr2}$

另一方面,在R中,我所要做的就是as.Date(string),并且我以日期的形式得到适当的日期。Python有这样的东西吗?在


Tags: 字符串info内容datestringasgreenone
3条回答

如果知道字符串中的位置和日期格式,则可以将切片与strptime一起使用:

import datetime as dt

>>> dt.datetime.strptime(string[:10], '%Y-%m-%d').date()
datetime.date(2014, 12, 4)

如果要使用像熊猫这样的软件包:

^{pr2}$

您还可以使用dateutil包:

from dateutil.parser import parse

parse(string[:10]).date()
datetime.date(2014, 12, 4)

dateutilfuzzy参数正是用于此目的:

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)

结果是:

^{pr2}$

如果只需要日期,只需使用dt.date()返回日期对象。在

注意,如果字符串中还有其他可能是日期一部分的内容(例如单词March或其他),这将给解析器带来问题。在

如果要查看它跳过的内容,请使用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解析为:

(' ', " <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()方法,只获取日期部分。在

相关问题 更多 >