Split Datetime Column into a Date and Time Python

17,882

Solution 1

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]

Solution 2

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
Share:
17,882
Alexis
Author by

Alexis

Analyst at UC Berkeley using Python

Updated on June 23, 2022

Comments

  • Alexis
    Alexis almost 2 years

    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!

    • EdChum
      EdChum almost 10 years
      Does it work without the format string : posts['Date']=pd.to_datetime(posts['Time'])?
    • shaktimaan
      shaktimaan almost 10 years
      Have you tried %Y-%m-%d %H:%M:%S.%f for format?