Description
Pandas version checks
-
I have checked that this issue has not already been reported.
-
I have confirmed this bug exists on the latest version of pandas.
-
I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import pandas as pd
# ONLY WORKING CONVERSION:
df = pd.DataFrame({'time': pd.to_datetime(['2021-01-01 12:00:00', '2021-01-01 12:00:01', '2021-01-01 12:00:02']), 'value': [1, 2, 3]})
df['time'] = df['time'].astype('M8[us]')
print(df.dtypes)
# time datetime64[us]
# value int64
# dtype: object
# NON-WORKING CONVERSIONS
df = pd.DataFrame({'time': pd.to_datetime(['2021-01-01 12:00:00', '2021-01-01 12:00:01', '2021-01-01 12:00:02']),
'value': [1, 2, 3]})
df.iloc[:, 0] = df.iloc[:, 0].astype('M8[us]')
print(df.dtypes)
# time datetime64[ns]
# value int64
# dtype: object
df = pd.DataFrame({'time': pd.to_datetime(['2021-01-01 12:00:00', '2021-01-01 12:00:01', '2021-01-01 12:00:02']),
'value': [1, 2, 3]})
df.loc[:, ['time']] = df.loc[:, ['time']].astype('M8[us]')
print(df.dtypes)
# time datetime64[ns]
# value int64
# dtype: object
df = pd.DataFrame({'time': pd.to_datetime(['2021-01-01 12:00:00', '2021-01-01 12:00:01', '2021-01-01 12:00:02']),
'value': [1, 2, 3]})
idxs = [0]
axis = 1
df.iloc(axis=axis)[idxs] = df.iloc(axis=axis)[idxs].astype('M8[us]')
print(df.dtypes)
# time datetime64[ns]
# value int64
# dtype: object
Issue Description
Conversion of columns (/rows) between datetime dtypes with different precision does not change the datatype of the columns (except for in the simplest case).
The absurd is that if I were to change the dtype of the "value" column in the above example, all of these example would've worked.
Expected Behavior
All printouts should be the same as the first:
time datetime64[us]
value int64
dtype: object
Installed Versions
INSTALLED VERSIONS
commit : bdc79c1
python : 3.9.18.final.0
python-bits : 64
OS : Linux
OS-release : 5.15.0-91-generic
Version : #101~20.04.1-Ubuntu SMP Thu Nov 16 14:22:28 UTC 2023
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_IL
LOCALE : en_IL.UTF-8
pandas : 2.2.1
numpy : 1.24.4
pytz : 2023.3.post1
dateutil : 2.8.2
setuptools : 68.2.2
pip : 23.3
Cython : 3.0.6
pytest : 7.4.3
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : 2.8.6
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None