Skip to content Skip to sidebar Skip to footer

How To Convert A Column Of Numbers Into A Date In A Dataframe In Python

My dataframe contains a column for dates. It looks like this: Index Date 0 12018 1 102018 2 32018 3 122018 4 112019 5 32019 6 4201

Solution 1:

I think to_datetime with a specified format should be enough:

df['Date'] = pd.to_datetime(df['Date'], format='%m%Y')
print (df)
   Index       Date
0      0 2018-01-01
1      1 2018-10-01
2      2 2018-03-01
3      3 2018-12-01
4      4 2019-11-01
5      5 2019-03-01
6      6 2019-04-01

print (df.dtypes)
Index             int64
Date     datetime64[ns]
dtype: object

Thank you @Vivek Kalyanarangan for solution - add strftime for custom string format (but lost datetimes):

df['Date'] = pd.to_datetime(df['Date'], format='%m%Y').dt.strftime('%d-%m-%Y')
print (df)
   Index        Date
00  01-01-201811  01-10-201822  01-03-201833  01-12-201844  01-11-201955  01-03-201966  01-04-2019print (df.dtypes)
Index     int64
Date     object
dtype: objectprint (df['Date'].apply(type))
0    <class'str'>
1    <class'str'>
2    <class'str'>
3    <class'str'>
4    <class'str'>
5    <class'str'>
6    <class'str'>
Name: Date, dtype: object

Post a Comment for "How To Convert A Column Of Numbers Into A Date In A Dataframe In Python"