When upgrading from pandas version 1 to 2.0.0, I suddenly get a ValueError
in a script that worked fine before upgrading pandas to version 2:
ValueError: Cannot convert from timedelta64[ns] to timedelta64[D].
Supported resolutions are 's', 'ms', 'us', 'ns'
This is a minimally reproducible example:
import pandas as pd
df = pd.DataFrame({'designation_date': ['2021-01-01', '2021-01-02']})
df['recency'] = pd.to_datetime('today') - pd.to_datetime(df['designation_date'])
df['recency'] = df['recency'].astype('timedelta64[D]')
What do I need to replace df['recency'].astype('timedelta64[D]')
with so that the code works with pandas v2?
Using astype('timedelta64[D]')
is used quite a bit in answers across SO, e.g. here.
Use the .dt.days
accessor instead of astype('timedelta64[D])
:
df['recency'] = df['recency'].dt.days
The change in behaviour from v1 to v2 is documented here in the Pandas changelog.