深度阅读

How to reformat dates in pandas?

作者
作者
2023年08月22日
更新时间
12.1 分钟
阅读时间
0
阅读量

To reformat dates in a pandas DataFrame, you first need to convert them to the datetime format using pd.to_datetime(). Once the dates are in the datetime format, you can use the .dt accessor to access different date components such as year, month, day, and time. Finally, you can use the strftime() method to reformat the dates.

Here is an example of how to reformat dates in pandas:

import pandas as pd

# Create a DataFrame with a date column
df = pd.DataFrame({'date': ['2022-08-15', '2022-08-16', '2022-08-17'], 'value': [1, 2, 3]})

# Convert the date column to datetime format
df['date'] = pd.to_datetime(df['date'])

# Reformat the date column as dd-mm-yyyy
df['date'] = df['date'].dt.strftime('%d-%m-%Y')

# Print the updated DataFrame
print(df)

In this code, we create a pandas DataFrame df with a date column in the YYYY-MM-DD format. We first convert the date column to the datetime format using pd.to_datetime(). Then, we use the .dt accessor to access the day, month, and year components of the date, and use .strftime() to reformat the date as dd-mm-yyyy.

Note that the strftime() function uses the same format codes as the standard Python datetime module.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。