w3resource
Python Pandas Exercises

Pandas: Convert DataFrame column type from string to datetime

Pandas: DataFrame Exercise-41 with Solution

Write a Pandas program to convert DataFrame column type from string to datetime.
Sample data:
String Date:
0 3/11/2000
1 3/12/2000
2 3/13/2000
dtype: object
Original DataFrame (string to datetime):
0
0 2000-03-11
1 2000-03-12
2 2000-03-13

Sample Solution :

Python Code :

import pandas as pd
import numpy as np
s = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000'])
print("String Date:")
print(s)
r = pd.to_datetime(pd.Series(s))
df = pd.DataFrame(r)
print("Original DataFrame (string to datetime):")
print(df)

Sample Output:

 String Date:
0    3/11/2000
1    3/12/2000
2    3/13/2000
dtype: object
Original DataFrame (string to datetime):
           0
0 2000-03-11
1 2000-03-12
2 2000-03-13             

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to shuffle a given DataFrame rows.
Next: Write a Pandas program to rename a specific column name in a given DataFrame.

What is the difficulty level of this exercise?