简体   繁体   中英

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).

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

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

I got the following error:

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?

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

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

Let's use pandas 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'. So, use pandas Timestamp to create the same object type as DateTimeIndex.

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

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

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

and then:

date.days 

will store result (type - int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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