Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting object to datetime format in python

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!

like image 590
Sdotsey Avatar asked Jul 12 '16 16:07

Sdotsey


People also ask

How do you convert an object to a date in python?

The date column is indeed a string, which—remember—is denoted as an object type in Python. You can convert it to the datetime type with the . to_datetime() method in pandas .

How do you convert an object to time in python?

We can use time() function alongwith strptime() function to convert string to time object.

Which of the following methods is used to convert date like strings into datetime objects?

Timedelta('1 days 2 hours') do to DatetimeIndex object d, defined below? d = pd.


Video Answer


1 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').

like image 81
A. Garcia-Raboso Avatar answered Oct 06 '22 18:10

A. Garcia-Raboso