2

I have a dataframe with a column containing strings that represent date and time like this:

0    Fri Oct 19 17:42:31 2018
1    Fri Oct 19 17:42:31 2018
2    Fri Oct 19 17:42:31 2018
3    Fri Oct 19 17:42:31 2018
4    Fri Oct 19 17:42:31 2018

How can I parse the strings to get the time and the data in datetime format?

Despe1990
  • 595
  • 1
  • 3
  • 21

2 Answers2

4

Just use pd.to_datetime():

import pandas as pd

df = pd.DataFrame([
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018']],
columns=['Date'])

df['Date'] = pd.to_datetime(df['Date'])

Yields:

                 Date
0 2018-10-19 17:42:31
1 2018-10-19 17:42:31
2 2018-10-19 17:42:31
3 2018-10-19 17:42:31
4 2018-10-19 17:42:31

Per @ALollz's comment, you can specify the format to improve performance:

df['Date'] = pd.to_datetime(df['Date'], format='%a %b %d %H:%M:%S %Y')
rahlf23
  • 8,869
  • 4
  • 24
  • 54
1

You can try df['column_name']=pd.to_datetime(df['column_name']). This will convert the datetime you have in string to datetime object and store in the same column. Let me know if this works on your dataframe. You have to import pandas as pd for this to work though.

Harikrishna
  • 1,100
  • 5
  • 13
  • 30