w3resource

Pandas: Convert DataFrame column type from string to datetime


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             

Explanation:

The above code first creates a Pandas Series object s containing three strings that represent dates in 'month/day/year' format.

r = pd.to_datetime(pd.Series(s)): This line uses the pd.to_datetime() method to convert each string date into a Pandas datetime object, and then create a new Pandas Series object ‘r’ containing these datetime objects.

df = pd.DataFrame(r): Finally, the code creates a new Pandas DataFrame ‘df’ from ‘r’ by passing it as the only column of the DataFrame. The resulting DataFrame df contains a single column of datetime objects representing the dates from the original Series ‘s’

Python-Pandas 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?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.