w3resource

Pandas: Convert DataFrame column type from string to datetime


41. 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’


For more Practice: Solve these Related Problems:

  • Write a Pandas program to convert a DataFrame column from string dates to datetime objects and then set it as the index.
  • Write a Pandas program to change a column’s data type from string to datetime and then extract the month and year.
  • Write a Pandas program to convert date strings in multiple formats to datetime and then sort the DataFrame by this column.
  • Write a Pandas program to transform a column of string dates into datetime objects and then compute the time difference between consecutive rows.

Go to:


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.

Python-Pandas Code Editor:

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

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.