深度阅读

How to convert a column of strings to datetime in a Pandas DataFrame?

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

To convert a column of strings to datetime in a Pandas DataFrame, you can use the pandas.to_datetime() method. Here is an example:

import pandas as pd

# Create a sample DataFrame with a column of strings
data = {'date': ['2021-12-10', '2022-01-05', '2022-02-15']}
df = pd.DataFrame(data)

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

# Print the updated DataFrame
print(df)

This will output the following DataFrame with the ‘date’ column in datetime format:

date
0 2021-12-10
1 2022-01-05
2 2022-02-15

You can also specify the format of the strings using the format parameter. For example, if your strings are in the ‘yyyymmdd’ format, you can modify the code like so:

df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')

This will convert the ‘date’ column from the ‘yyyymmdd’ string format to datetime format.

相关标签

博客作者

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