Convert datetime string to new columns of Day, Month, Year in pandas data frame

霸气de小男生 提交于 2019-12-05 16:15:28

Just split the time with - or T and the first three elements should correspond to the year, month and day column, concatenate it with the other two columns will get what you need:

pd.concat([df.drop('time', axis = 1), 
          (df.time.str.split("-|T").str[:3].apply(pd.Series)
          .rename(columns={0:'year', 1:'month', 2:'day'}))], axis = 1)


An alternative close to @nlassaux's approach would be:

df['time'] = pd.to_datetime(df['time'])   
df['year'] = df.time.dt.year
df['month'] = df.time.dt.month
df['day'] = df.time.dt.day
df.drop('time', axis=1, inplace=True)

The cleanest way is to use builtin pandas datetime functions.

First, convert the column to datetime:

df["time"] = pd.to_datetime(df["time"])

Then, extract your information:

df["day"] = df['time'].map(lambda x: x.day)
df["month"] = df['time'].map(lambda x: x.month)
df["year"] = df['time'].map(lambda x: x.year)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!