w3resource

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



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
    if x[idx] % 2 == 0:
        result.append(x[idx] * 2)
    else:
        result.append(x[idx])
result

Output:

[1, 4, 3, 8, 5, 12]
[(element * 2 if element % 2 == 0 else element) for element in x]

Output:

[1, 4, 3, 8, 5, 12]
[element * 2 for element in x if element % 2 == 0]

Output:

[4, 8, 12]