在 Pandas 中将 DatetimeIndex 转换为 datetime.date?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52278464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:01:28  来源:igfitidea点击:

Convert DatetimeIndex to datetime.date in pandas?

pythonpandas

提问by Sid

I am trying to subtract todays date from a column in pandas to get the number of days(as an integer).

我试图从 Pandas 的列中减去今天的日期以获得天数(作为整数)。

I first converted the date's in column(ex: 27-Sep-2018) using pd.to_datetime.

我首先使用pd.to_datetime.

df['Date'] - datetime.datetime.now().date()

df['Date'] - datetime.datetime.now().date()

I got the following error:

我收到以下错误:

TypeError: unsupported operand type(s) for -: 'DatetimeIndex' and 'datetime.date'

类型错误:不支持的操作数类型 -:'DatetimeIndex' 和 'datetime.date'

I am trying to figure out how to get this to work, also converting the days to integer?

我想弄清楚如何让它工作,还将天数转换为整数?

TIA

TIA

回答by SAKURA

I think the issue may be due to you subtracting a pandas datetime object from a date object (which does not include the time). You can try this:

我认为问题可能是由于您从日期对象(不包括时间)中减去了Pandas日期时间对象。你可以试试这个:

df['Date_2'] = pd.to_datetime(df['Date']).dt.date

Now doing the calculation: df['Date_2'] - datetime.datetime.now().date()should work.

现在做计算:df['Date_2'] - datetime.datetime.now().date()应该可以。

回答by Scott Boston

Let's use pandas Timestamp.now():

让我们使用PandasTimestamp.now()

s = pd.Series('27-Sep-2018')

s = pd.to_datetime(s)

(s - pd.Timestamp.now()).dt.days

Output:

输出:

0     15
dtype: int64

Note: The error is stating that you can't subtract object type DatetimeIndex from object 'datetime.date'. So, use pandas Timestamp to create the same object type as DateTimeIndex.

注意:错误表明您不能从对象“datetime.date”中减去对象类型 DatetimeIndex。因此,使用 pandas Timestamp 创建与 DateTimeIndex 相同的对象类型。

回答by Miko?aj Henklewski

try to use datetime.strptime() function to convert it.

尝试使用 datetime.strptime() 函数来转换它。

in your ex='27-Sep-2018' it would look like these:

在您的 ex='27-Sep-2018' 中,它看起来像这样:

from datetime import datetime
ex='27-Sep-2018'
date = datetime.strptime(ex, '%d-%b-%Y')

and then:

进而:

date.days 

will store result (type - int)

将存储结果(类型 - int)