假设我有一个Dataframe:
df = {'date':['20170101', '20170102', '20170103', '20170104']}
我想将’20170101’转换为’2017-01-01 00:00:00′
我怎样才能实现它?
最佳答案 如果你有一个pandas.DataFrame,你可以这样做:
码:
pd.to_datetime(df['date'], format='%Y%m%d')
测试代码:
df = pd.DataFrame({'date':['20170101', '20170102', '20170103', '20170104']})
df['date2'] = df['date'].apply(lambda d: dt.datetime.strptime(d, '%Y%m%d'))
df['date3'] = pd.to_datetime(df['date'], format='%Y%m%d')
print(df)
结果:
date date2 date3
0 20170101 2017-01-01 2017-01-01
1 20170102 2017-01-02 2017-01-02
2 20170103 2017-01-03 2017-01-03
3 20170104 2017-01-04 2017-01-04