Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing certain column type to date from datetime

I have a df in which I want to change certain columns type to date from datetime:

field   category    2022-01-10 00:00:00     2022-01-17 00:00:00     2022-01-24 00:00:00
A       10          500                     700                     500
B       15          60                      70                      50

I am trying to achieve this:

field   category    2022-01-10      2022-01-17      2022-01-24
A       10          500             700             500
B       15          60              70              50

Because during concat with other df the column type changes from 2021-11-19 to 2021-11-19 00:00:00.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

From this answer I tried::

df.loc[:,pd.to_datetime('2022-01-10 00:00:00') : pd.to_datetime('2022-06-20 00:00:00')].columns = 
                                                 pd.to_datetime(df.loc[:,pd.to_datetime('2022-01-10 00:00:00') : 
                                                 pd.to_datetime('2022-06-20 00:00:00')].columns)
                                                 .strftime('%Y-%m-%d')

But this does not change the type of the column which I cant understand why because

pd.to_datetime(df.loc[:,pd.to_datetime('2022-01-10 00:00:00') : pd.to_datetime('2022-06-20 00:00:00')].columns).strftime('%Y-%m-%d')

Return:

Index(['2022-01-10', '2022-01-17', '2022-01-24')]

>Solution :

In your column index you mix string (‘field’ and ‘category’) and timestamp (other columns) so your column index is an Index not a DatetimeIndex.

>>> df.columns
Index([            'field',          'category', 2022-01-10 00:00:00,
       2022-01-17 00:00:00, 2022-01-24 00:00:00],
      dtype='object')

>>> [type(c) for c in df.columns]
[str,
 str,
 pandas._libs.tslibs.timestamps.Timestamp,
 pandas._libs.tslibs.timestamps.Timestamp,
 pandas._libs.tslibs.timestamps.Timestamp]

The default string representation of Timestamp is YYYY-mm-dd HH:MM:SS while the default representation of each value of a DatetimeIndex can be YYYY-mm-dd only (if possible).

To get the date format, you have to cast your Timestamp to string.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading