Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a DataFrame column with datetimes into two columns: one with dates and one with times of the day?

I have a data frame called data, which has a column Dates like this,

                 Dates
0  2015-05-13 23:53:00
1  2015-05-13 23:53:00
2  2015-05-13 23:33:00
3  2015-05-13 23:30:00
4  2015-05-13 23:30:00

I know how to add a column to data frame, but how to divide Dates to

          Day         Time
0  2015-05-13     23:53:00
1  2015-05-13     23:53:00
2  2015-05-13     23:33:00
3  2015-05-13     23:30:00
4  2015-05-13     23:30:00
like image 614
Kevin217 Avatar asked Feb 21 '16 16:02

Kevin217


2 Answers

If your series is s, then this will create such a DataFrame:

pd.DataFrame({
    'date': pd.to_datetime(s).dt.date,
    'time': pd.to_datetime(s).dt.time})

as once you convert the series using pd.to_datetime, then the dt member can be used to extract the parts.


Example

import pandas as pd

s = pd.Series(['2015-05-13 23:53:00', '2015-05-13 23:53:00'])
>>> pd.DataFrame({
    'date': pd.to_datetime(s).dt.date,
    'time': pd.to_datetime(s).dt.time})
    date    time
0   2015-05-13  23:53:00
1   2015-05-13  23:53:00
like image 172
Ami Tavory Avatar answered Sep 16 '22 22:09

Ami Tavory


If your Dates column is a string:

data['Day'], data['Time'] = zip(*data.Dates.str.split())

>>> data
                 Dates         Day      Time
0  2015-05-13 23:53:00  2015-05-13  23:53:00
1  2015-05-13 23:53:00  2015-05-13  23:53:00
2  2015-05-13 23:33:00  2015-05-13  23:33:00
3  2015-05-13 23:33:00  2015-05-13  23:33:00
4  2015-05-13 23:33:00  2015-05-13  23:33:00

If it is a timestamp:

data['Day'], data['Time'] = zip(*[(d.date(), d.time()) for d in data.Dates])
like image 33
Alexander Avatar answered Sep 18 '22 22:09

Alexander