Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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.

Solution 2:

Let's use pandas Timestamp.now():

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

s = pd.to_datetime(s)

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

Output:

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

Solution 3:

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)

Solution 4:

Post a Comment for "Convert Datetimeindex To Datetime.date In Pandas"