25

Below is the first row of my csv DateTime column:

Mon Nov 02 20:37:10 GMT+00:00 2015

The DateTime column is currently an object and I want to convert it to datetime format so that I can get the date to appear as 2015-11-02 and I will create a separate column for the time.

The code I am using to convert the column to date time format is:

for item, frame in df['DateTime'].iteritems():
     datetime.datetime.strptime(df['DateTime'], "%a-%b-%d-%H-%M-%S-%Z-%Y")

I am getting this error:

> TypeError: must be str, not Series

Any help would be greatly appreciated!

2
  • 1
    @bernie: that yields AttributeError: 'Series' object has no attribute 'to_datetime', Commented Jul 12, 2016 at 16:11
  • 1
    Ah, thanks. +1 to your answer. Commented Jul 12, 2016 at 16:12

3 Answers 3

69

Use pd.to_datetime():

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

For example,

pd.to_datetime('Mon Nov 02 20:37:10 GMT+00:00 2015')

produces Timestamp('2015-11-02 20:37:10').

Sign up to request clarification or add additional context in comments.

1 Comment

Any idea what to do where there is a huge list, and one time is nan? Should i first try to find and edit/change that one value to something or is there a nice trick?
0

Another solution is to pass errors parameter as per below and its application

df['DateTime'] = pd.to_datetime(df['DateTime'], errors='coerce')

errors{‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’

  1. If ‘raise’, then invalid parsing will raise an exception.
  2. If ‘coerce’, then invalid parsing will be set as NaN.
  3. If ‘ignore’, then invalid parsing will return the input.

Comments

0

I would like to further add to 'Alicia Garcia-Raboso', that after conversion we may need to extract Year, Month . We can do this by df ['DateTime'] = df['DateTime'].dt.year, and so on. This is especially useful when dealing with dataframes.

1 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.