Search code examples
python-3.xpandasdatetimetype-conversiontimestamp

Convert column to timestamp - Pandas Dataframe


I have a Pandas DataFrame that has date values stored in 2 columns in the below format:

col1: 04-APR-2018 11:04:29
col2: 2018040415203 

How could I convert this to a time stamp. Dtype of both of these columns is object.


Solution

  • For the first format you can simply pass to_datetime, for the latter you need to explicitly describe the date format (see the table of available directives in the python docs):

    In [21]: df
    Out[21]:
                       col1           col2
    0  04-APR-2018 11:04:29  2018040415203
    
    In [22]: pd.to_datetime(df.col1)
    Out[22]:
    0   2018-04-04 11:04:29
    Name: col1, dtype: datetime64[ns]
    
    In [23]: pd.to_datetime(df.col2, format="%Y%m%d%H%M%S")
    Out[23]:
    0   2018-04-04 15:20:03
    Name: col2, dtype: datetime64[ns]