I\'m looking for a function analogous to np.interp
that can work with datetime
objects.
For example:
import datetime, numpy
I'm providing this as a complement to @rchang's answer for those wanting to do this all in Pandas. This function takes a pandas series containing dates and returns a new series with the values converted to 'number of days' after a specified date.
def convert_dates_to_days(dates, start_date=None, name='Day'):
"""Converts a series of dates to a series of float values that
represent days since start_date.
"""
if start_date:
ts0 = pd.Timestamp(start_date).timestamp()
else:
ts0 = 0
return ((dates.apply(pd.Timestamp.timestamp) -
ts0)/(24*3600)).rename(name)
Not sure it will work with times or if it is immune to the time-zone pitfalls mentioned above. But I think as long as you provide a start date in the same time zone, which is subtracted from all the timestamp values, you should be okay.
Here's how I used it:
from scipy.interpolate import interp1d
data = pd.DataFrame({
'Date': pd.date_range('2018-01-01', '2018-01-22', freq='7D'),
'Value': np.random.randn(4)
})
x = convert_dates_to_days(data.Date, start_date='2018-01-01')
y = data.Value
f2 = interp1d(x, y, kind='cubic')
all_dates = pd.Series(pd.date_range('2018-01-01', '2018-01-22'))
x_all = convert_dates_to_days(all_dates, start_date='2018-01-01')
plt.plot(all_dates, f2(x_all), '-')
data.set_index('Date')['Value'].plot(style='o')
plt.grid()
plt.savefig("interp_demo.png")
plt.show()
It seems to work...