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?
To convert the DateTimeIndex to Series, use the DateTimeIndex. to_series() method.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With