Search code examples
pythonpandasdataframedatetimetype-conversion

Convert DataFrame column type from string to datetime


How can I convert a DataFrame column of strings (in dd/mm/yyyy format) to datetime dtype?


Solution

  • The easiest way is to use to_datetime:

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

    It also offers a dayfirst argument for European times (but beware this isn't strict).

    Here it is in action:

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

    You can pass a specific format:

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