在 Pandas 中将 DatetimeIndex 转换为 datetime.date? [英] Convert DatetimeIndex to datetime.date in pandas?
问题描述
我试图从 Pandas 的列中减去今天的日期以获得天数(作为整数).
I am trying to subtract todays date from a column in pandas to get the number of days(as an integer).
我首先使用 pd.to_datetime
转换了列中的日期(例如:27-Sep-2018).
I first converted the date's in column(ex: 27-Sep-2018) using pd.to_datetime
.
df['Date'] - datetime.datetime.now().date()
我收到以下错误:
TypeError: 不支持的操作数类型 -: 'DatetimeIndex' 和 'datetime.date'
TypeError: unsupported operand type(s) for -: 'DatetimeIndex' and 'datetime.date'
我想弄清楚如何让它工作,并将天数转换为整数?
I am trying to figure out how to get this to work, also converting the days to integer?
TIA
推荐答案
我认为问题可能是由于您从日期对象(不包括时间)中减去了 Pandas datetime 对象.你可以试试这个:
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:
df['Date_2'] = pd.to_datetime(df['Date']).dt.date
现在进行计算:df['Date_2'] - datetime.datetime.now().date()
应该可以工作.
Now doing the calculation: df['Date_2'] - datetime.datetime.now().date()
should work.
这篇关于在 Pandas 中将 DatetimeIndex 转换为 datetime.date?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!