且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中将一列数字转换为数据框中的日期

更新时间:2022-12-12 08:34:45

我认为格式的"nofollow noreferrer> to_datetime 应该足够了:

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

感谢@Vivek Kalyanarangan解决方案-添加

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
0      0  01-01-2018
1      1  01-10-2018
2      2  01-03-2018
3      3  01-12-2018
4      4  01-11-2019
5      5  01-03-2019
6      6  01-04-2019

print (df.dtypes)
Index     int64
Date     object
dtype: object

print (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