Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DataFrame column type from string to datetime

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

like image 496
perigee Avatar asked Jun 16 '13 15:06

perigee


People also ask

How do I turn a column into datetime?

In Pandas, you can convert a column (string/object or integer type) to datetime using the to_datetime() and astype() methods. Furthermore, you can also specify the data type (e.g., datetime) when reading your data from an external source, such as CSV or Excel.


1 Answers

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] 
like image 54
Andy Hayden Avatar answered Sep 24 '22 00:09

Andy Hayden