Python ProgrammingPython Programming

How to convert column with dtype as Int to DateTime in Pandas Dataframe?

Alter column data type from Unixtime Stamp to Datetime:

Pandas will always store strings as objects.

import pandas as pd

df = pd.DataFrame({'DateOFBirth': [1349720105, 1349806505, 1349892905,
                                   1349979305, 1350065705, 1349792905,
                                   1349730105],
                   'State': ['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
                   },
                  index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean',
                         'Christina', 'Cornelia'])

print("\n----------------Before---------------\n")
print(df.dtypes)
print(df)

df['DateOFBirth'] = pd.to_datetime(df['DateOFBirth'], unit='s')

print("\n----------------After----------------\n")
print(df.dtypes)
print(df)



C:\python\pandas examples>pycodestyle --first example17.py
 
C:\python\pandas examples>python example17.py
 
----------------Before---------------
 
DateOFBirth     int64
State          object
dtype: object
           DateOFBirth State
Jane        1349720105    NY
Nick        1349806505    TX
Aaron       1349892905    FL
Penelope    1349979305    AL
Dean        1350065705    AK
Christina   1349792905    TX
Cornelia    1349730105    TX
 
----------------After----------------
 
DateOFBirth    datetime64[ns]
State                  object
dtype: object
                  DateOFBirth State
Jane      2012-10-08 18:15:05    NY
Nick      2012-10-09 18:15:05    TX
Aaron     2012-10-10 18:15:05    FL
Penelope  2012-10-11 18:15:05    AL
Dean      2012-10-12 18:15:05    AK
Christina 2012-10-09 14:28:25    TX
Cornelia  2012-10-08 21:01:45    TX
 
C:\python\pandas examples>