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?

0

2 Answers 2

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')
Sign up to request clarification or add additional context in comments.

2 Comments

And you can speed up the parsing greatly by specifying format='%a %b %d %H:%M:%S %Y'
Thanks to both of you
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.