Ask Your Question
3

How can I change the format of a datetime column in pandas from yyyy-mm-dd to YYYYMMDD?

asked 2022-03-26 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-12-25 05:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-26 11:00:00 +0000

Seen: 10 times

Last updated: Dec 25 '22