简体   繁体   English

在 Pandas 中将 DatetimeIndex 转换为 datetime.date

[英]Convert DatetimeIndex to datetime.date in pandas

I am trying to subtract today's 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转换了列中的日期(例如:27-Sep-2018)。

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?我想弄清楚如何让它工作,还将天数转换为整数?

I think the issue may be due to you subtracting a pandas datetime object from a date object (which does not include the time). 我认为问题可能是由于您从日期对象(不包括时间)中减去了熊猫的datetime对象。 You can try this: 您可以尝试以下方法:

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()应该可以工作。

Let's use pandas Timestamp.now() : 让我们使用熊猫Timestamp.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'. 注意:该错误说明您无法从对象“ datetime.date”中减去对象类型DatetimeIndex。 So, use pandas Timestamp to create the same object type as DateTimeIndex. 因此,使用pandas Timestamp创建与DateTimeIndex相同的对象类型。

try to use datetime.strptime() function to convert it. 尝试使用datetime.strptime()函数进行转换。

in your ex='27-Sep-2018' it would look like these: 在您的ex ='2018年9月27日'中,它看起来像这样:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM