Python中是否有类似于R语言中的as.Date()函数?

3

假设我们有一个字符串:

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

在Python中,我需要移除除了2014-12-04以外的所有内容,然后使用。
time.mktime(datetime.datetime.strptime(string, "%Y-%m-%d").timetuple())

另一方面,在R中,我只需要使用as.Date(string),就可以得到适当的日期,以日期形式表示。Python有类似的东西吗?


4
除了 datetime.strptime(string.partition(' ')[0], '%Y-%m-%d')) 以外,你是指什么?实际上你需要挑选出一个可能的日期候选项(如果有多个怎么办,更不用说不同的格式了),然后对其进行解析。 - Jon Clements
第三方库dateutil可以帮助解析各种格式的日期,但是您传递给它的字符串仍然需要看起来像一个日期。我认为它不会查找字符串中类似日期的内容并尝试解析。 - mgilson
@mgilson 不行——它仍然期望字符串只包含日期…… - Jon Clements
@JonClements -- 对的,这就是我所说的“但你传递给它的字符串仍然需要看起来像一个日期”。我想我在下一句话中应该更加具体...我知道它不会在字符串中寻找类似日期的东西,然后尝试解析它 :-) - mgilson
参数 fuzzy 忽略字符串中所有看起来不像日期的内容。 - Paul
4个回答

4

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

import datetime as dt

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

如果您想使用像pandas这样的软件包:
>>> pd.to_datetime(string[:10])
Timestamp('2014-12-04 00:00:00')

你也可以使用 dateutil 包:
from dateutil.parser import parse

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

3
fuzzy参数用于此目的:将其用于dateutil
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)

结果如下:
datetime.datetime(2014, 12, 4, 4, 7, 59)

如果你只想要日期,只需使用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.")

1

要在任意文本中查找日期/时间,您可以尝试使用parsedatetime模块

>>> 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() 方法,以获取仅日期部分。

1

是的,在Python中也有类似于(R)中as.Date()的东西。请尝试以下操作:

true_time = pd.to_datetime(your_array, origin ='2000/1/1', unit = 'D')

使用origin可以指定参考日期; 使用unit可以指定特定的步骤(例如 D-天,ms-毫秒等)。 同样,在这种情况下,your_array可以是一个列表。 此外还有更多信息 here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接