Search code examples
pythondatetimepython-datetime

Conversion of set of numbers into Date Format using Python


I have a dataframe named 'train' with column ID which represents 'date' in a very unusual manner. For e.g. certain entry in ID:

For example, the value of ID 2013043002 represents the date 30/04/2013 
02:00:00

First 4 digits represents year, subsequent 2 digits represent month and day respectively. And last two digits represent time.

So I want to convert this into proper date time format to perform time series analysis.


Solution

  • Use to_datetime with parameter format - check http://strftime.org/:

    df = pd.DataFrame({'ID':[2013043002,2013043002]})
    
    df['ID'] = pd.to_datetime(df['ID'], format='%Y%m%d%H')
    print(df)
                       ID
    0 2013-04-30 02:00:00
    1 2013-04-30 02:00:00
    
    print(df['ID'].dtype)
    datetime64[ns]