Converting object to datetime format in python
Question:
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!
Answers:
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')
.
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’
- If ‘raise’, then invalid parsing will raise an exception.
- If ‘coerce’, then invalid parsing will be set as NaN.
- If ‘ignore’, then invalid parsing will return the input.
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!
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')
.
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’
- If ‘raise’, then invalid parsing will raise an exception.
- If ‘coerce’, then invalid parsing will be set as NaN.
- If ‘ignore’, then invalid parsing will return the input.