Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the strftime method in pandas to format the datetime column. Here's an example:

import pandas as pd

# create a sample dataframe with a datetime column
df = pd.DataFrame({'date': ['2020-05-15', '2021-01-01', '2022-06-30'], 'value': [10, 20, 30]})
df['date'] = pd.to_datetime(df['date'])

# format the datetime column as YYYYMMDD
df['date'] = df['date'].dt.strftime('%Y%m%d')

print(df)

Output:

       date  value
0  20200515     10
1  20210101     20
2  20220630     30

In the example, we first convert the 'date' column to datetime format using pd.to_datetime(). Then we use the strftime method with a formatting string of '%Y%m%d' to generate the desired format of YYYYMMDD. Finally, we assign the formatted datetime values back into the 'date' column.