How to convert int64 to datetime in pandas

17,463

You need a capital Y. See Python's strftime directives for a complete reference.

df = pd.DataFrame({'old_date': [20180501, 20181230, 20181001]})

df['new_date'] = pd.to_datetime(df['old_date'].astype(str), format='%Y%m%d')

print(df)

   old_date   new_date
0  20180501 2018-05-01
1  20181230 2018-12-30
2  20181001 2018-10-01
Share:
17,463

Related videos on Youtube

HHH
Author by

HHH

Updated on June 16, 2022

Comments

  • HHH
    HHH almost 2 years

    I have a pandas dataframe that has a column of type int64 but this columns represets date, e.g. 20180501. I'd like to convert this column to datetime and I'm having the following code but it returns an error message

     df['new_date'] = pd.to_datetime(df['old_date'].astype('str'), format = '%y%m%d')
    

    I'm getting the following error message

    ValueError: unconverted data remains: 0501
    

    How can I fix my code?

  • mirekphd
    mirekphd about 4 years
    Unfortunately with or without '.astype(str)' it has not effect (silent fail)... when trying to convert from '%Y-%m-%d' to '%d/%m/%Y'.