Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DatetimeIndex to datetime.date in pandas

Tags:

python

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?

like image 559
Sid Avatar asked Sep 11 '18 14:09

Sid


People also ask

How do I convert DateTimeIndex to series?

To convert the DateTimeIndex to Series, use the DateTimeIndex. to_series() method.

What is DateTimeIndex pandas?

DatetimeIndex [source] Immutable ndarray of datetime64 data, represented internally as int64, and which can be boxed to Timestamp objects that are subclasses of datetime and carry metadata such as frequency information.

How do I convert a string to a datetime in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.


2 Answers

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.

like image 97
SAKURA Avatar answered Oct 01 '22 14:10

SAKURA


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.

like image 21
Scott Boston Avatar answered Oct 01 '22 14:10

Scott Boston