Prudhvi Raj
Prudhvi Raj

Reputation: 21

how to change the data type date object to datetime in python?

In a train data set, datetime column is an object . First row of this column : 2009-06-15 17:26:21 UTC . I tried splitting the data

train['Date'] = train['pickup_datetime'].str.slice(0,11)

train['Time'] = test['pickup_datetime'].str.slice(11,19)

So that I can split the Date and time as two variables and change them to datetime data type. Tried lot of methods but could not get the result.

 train['Date']=pd.to_datetime(train['Date'], format='%Y-%b-%d')

Also tried spliting the date,time and UTC

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

Please suggest a code for this. I am a begginer.

Thanks in advance

Upvotes: 2

Views: 6574

Answers (1)

Fourier
Fourier

Reputation: 2993

I would try the following

import pandas as pd

#create some random dates matching your formatting
df = pd.DataFrame({"date": ["2009-06-15 17:26:21 UTC", "2010-08-16 19:26:21 UTC"]})
#convert to datetime objects
df["date"] = pd.to_datetime(df["date"])

print(df["date"].dt.date) #returns the date part without tz information
print(df["date"].dt.time) #returns the time part 

Output:

0    2009-06-15
1    2010-08-16
Name: date, dtype: object
0    17:26:21
1    19:26:21
Name: date, dtype: object

For further information feel free to consult the docs: dt.date dt.time

For your particular case:

#convert to datetime object
df['pickup_datetime']= pd.to_datetime(df['pickup_datetime'])

# seperate date and time 
df['Date'] = df['pickup_datetime'].dt.date
df['Time'] = df['pickup_datetime'].dt.time

Upvotes: 1

Related Questions