Write a program to separate date and time from the datetime column in Python Pandas

PythonPandasServer Side ProgrammingProgramming

Assume, you have datetime column in dataframe and the result for separating date and time as,

   datetime    date          time
0 2020-01-01 07:00:00 2020-01-06 07:00:00
1 2020-01-02 07:00:00 2020-01-06 07:00:00
2 2020-01-03 07:00:00 2020-01-06 07:00:00
3 2020-01-04 07:00:00 2020-01-06 07:00:00
4 2020-01-05 07:00:00 2020-01-06 07:00:00
5 2020-01-06 07:00:00 2020-01-06 07:00:00

To solve this, we will follow the below approaches −

Solution 1

  • Define a dataframe ‘datetime’ column using pd.date_range(). It is defined below,

pd.DataFrame({'datetime':pd.date_range('2020-01-01 07:00',periods=6)})
  • Set for loop d variable to access df[‘datetime’] column one by one.

  • Convert date and time from for loop and save it as df[‘date’] and df[‘time’]. It is defined below,

for d in df['datetime']:
   df['date'] = d.date()
   df['time'] = d.time()

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.DataFrame({'datetime':pd.date_range('2020-01-01 07:00',periods=6)})
print("DataFrame is:\n", df)
for d in df['datetime']:
   df['date'] = d.date()
   df['time'] = d.time()
print(df)

Output

DataFrame is:
             datetime
0 2020-01-01 07:10:00
1 2020-01-02 07:10:00
2 2020-01-03 07:10:00
3 2020-01-04 07:10:00
4 2020-01-05 07:10:00
5 2020-01-06 07:10:00
Date-time-hour-minutes :
             datetime    date      time
0 2020-01-01 07:10:00 2020-01-06 07:10:00
1 2020-01-02 07:10:00 2020-01-06 07:10:00
2 2020-01-03 07:10:00 2020-01-06 07:10:00
3 2020-01-04 07:10:00 2020-01-06 07:10:00
4 2020-01-05 07:10:00 2020-01-06 07:10:00
5 2020-01-06 07:10:00 2020-01-06 07:10:00

Solution 2

  • Define a dataframe

  • Apply pd.to_datetime() function inside df[‘datetime’] and select date using dt.date then save it as df[‘date’]

  • Apply pd.to_datetime() function inside df[‘datetime’] and select time using dt.time then save it as df[‘time’]

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.DataFrame({'datetime':pd.date_range('2020-01-01 07:10',periods=6)})
print("DataFrame is:\n", df)
df['date'] = pd.to_datetime(df['datetime']).dt.date
df['time'] = pd.to_datetime(df['datetime']).dt.time
print("Date-time-hour-minutes :\n", df)

Output

DataFrame is:
             datetime
0 2020-01-01 07:10:00
1 2020-01-02 07:10:00
2 2020-01-03 07:10:00
3 2020-01-04 07:10:00
4 2020-01-05 07:10:00
5 2020-01-06 07:10:00
Date-time-hour-minutes :
             datetime    date      time
0 2020-01-01 07:10:00 2020-01-06 07:10:00
1 2020-01-02 07:10:00 2020-01-06 07:10:00
2 2020-01-03 07:10:00 2020-01-06 07:10:00
3 2020-01-04 07:10:00 2020-01-06 07:10:00
4 2020-01-05 07:10:00 2020-01-06 07:10:00
5 2020-01-06 07:10:00 2020-01-06 07:10:00
raja
Published on 12-Feb-2021 10:57:49
Advertisements