Python ProgrammingPython Programming

How do I convert dates in a Pandas DataFrame to a DateTime data type?

Alter column data type from Object to Datetime64:

import pandas as pd

df = pd.DataFrame({'DateOfBirth': ['1986-11-11', '1999-05-12', '1976-01-01',
                                   '1986-06-01', '1983-06-04', '1990-03-07',
                                   '1999-07-09'],                   
                   'State': ['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
                   },
                  index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean',
                         'Christina', 'Cornelia'])

print("\n----------------Before---------------\n")
print(df.dtypes)
 
df['DateOfBirth'] = df['DateOfBirth'].astype('datetime64')
 
print("\n----------------After----------------\n")
print(df.dtypes)


C:\python\pandas examples>python example20.py
 
----------------Before---------------
 
DateOfBirth    object
State          object
dtype: object
 
----------------After----------------
 
DateOfBirth    datetime64[ns]
State                  object
dtype: object
 
C:\python\pandas examples>