How to convert a column of type integer to type datetime in python? -


i have column ("admit_year") of integers in dataframe. typical element in column looks like: 200110, 2001 = year , 10 = month. need convert column type datetime.

i succeeded in doing using clunky method below. offer more efficient way of writing code?

freshman['admit_year'] = freshman['admit_term'].astype(str).str.slice(0,4) freshman['admit_month'] = freshman['admit_term'].astype(str).str.slice(4,6) freshman['admit_date_str'] = freshman['admit_year']+'/'+freshman['admit_month'] freshman['admit_date'] = pd.to_datetime(freshman['admit_date_str'], format="%y/%m") 

note: believe question not answered here since dates not integer days.

just apply pd.to_datetime directly (the string conversion of) column, no need use string slicing here:

freshman['admit_date'] = pd.to_datetime(freshman['admit_date'].astype(str), format='%y%m') 

there no requirement there delimiter between digits:

>>> import pandas pd >>> df = pd.dataframe({'admit_date': [200110, 201604]}) >>> df['admit_date'] = pd.to_datetime(df['admit_date'].astype(str), format='%y%m') >>> df   admit_date 0 2001-10-01 1 2016-04-01 >>> df.dtypes admit_date    datetime64[ns] dtype: object 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -