Alexis
Alexis

Reputation: 9131

Split Datetime Column into a Date and Time Python

Hey so I have seen several questions about this, however, I have yet to successful solve my problem.

I have a single column Time in the format:

2014-07-17 00:59:27.400189+00

I want to split this into a two columns, Date and Hour.

I used

 posts['Date']=pd.to_datetime(posts['Time'],format='%Y-%m-%d %H:%M:%S')

However, I get an error

 ValueError: unconverted data remains: 400189+00

I am not sure what to label the last bit of information. I tried added %o but received another error

 ValueError: 'o' is a bad directive in format '%Y-%m-%d %H:%M:%S.%o'

Any ideas on how I can split these two values into two columns?

Thanks!

Upvotes: 3

Views: 21110

Answers (3)

Reshma2k
Reshma2k

Reputation: 179

import pandas as pd 

data = pd.DataFrame({'Date':['2014-07-17 00:59:27.400189+00']})

data['Dates'] = pd.to_datetime(data['Date'], format='%Y:%M:%D').dt.date
data['Hours'] = pd.to_datetime(data['Date'], format='%Y:%M:%D').dt.time

This gives me object type Date and Time. The expected column should be in date format

Upvotes: 0

Okroshiashvili
Okroshiashvili

Reputation: 4149

This worked for me

import pandas as pd 

data = pd.DataFrame({'Date':['2014-07-17 00:59:27.400189+00']})

data['Dates'] = pd.to_datetime(data['Date'], format='%Y:%M:%D').dt.date
data['Hours'] = pd.to_datetime(data['Date'], format='%Y:%M:%D').dt.time

You have to have

print(data)

Dates           Hours
2014-07-17     00:59:27.400189+00

Upvotes: 2

EdChum
EdChum

Reputation: 394041

the following worked for me:

In [18]:

import pandas as pd
df = pd.DataFrame({'Date':['2014-07-17 00:59:27.400189+00']})
df.dtypes
Out[18]:
Date    object
dtype: object
In [19]:

df['Date'] = pd.to_datetime(df['Date'])
df.dtypes
Out[19]:
Date    datetime64[ns]
dtype: object
In [20]:

df['Time'],df['Date']= df['Date'].apply(lambda x:x.time()), df['Date'].apply(lambda x:x.date())
df
Out[20]:
         Date             Time
0  2014-07-17  00:59:27.400189

[1 rows x 2 columns]

Upvotes: 7

Related Questions