Home >Backend Development >Python Tutorial >How to Convert a String Column to Datetime in Pandas?

How to Convert a String Column to Datetime in Pandas?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 17:34:13518browse

How to Convert a String Column to Datetime in Pandas?

Converting DataFrame Column Type from String to Datetime

Problem: How do we convert a DataFrame column containing strings in dd/mm/yyyy format to the datetime data type?

Solution:

The convenient method for this task is utilizing Pandas' to_datetime function:

df['col'] = pd.to_datetime(df['col'])

This method provides a dayfirst argument for accommodating European date formats.

Example:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

Specifying a custom format is also possible:

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]

The above is the detailed content of How to Convert a String Column to Datetime in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn