Python - Splitting timestamp column into separate date and time columns

Learn, how can we split timestamp column into separate date and time columns in Python pandas dataframe?
Submitted by Pranit Sharma, on August 23, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Datetime is a library in Python which is a collection of date and time. Inside Datetime, we can access date and time in any format, but usually, the date is present in the format of "yy-mm-dd" and time is present in the format of "HH:MM:SS".

Here,

  • yy means year
  • mm means month
  • dd means day
  • HH means hours
  • MM means minutes
  • SS means seconds

While accessing the date and time from datetime, we always get the date and time together, here, we will split this date and time separately.

Let us understand with the help of an example,

Python program to split timestamp column into separate date and time columns

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {'Time_to_be_splited':pd.date_range('2022-08-22 19:00', periods=10)}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")

# Splitting the date part from DataFrame
df['Date'] = [d.date() for d in df['Time_to_be_splited']]

# Splitting the time part from DataFrame
df['Time'] = [d.time() for d in df['Time_to_be_splited']]

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Splitting timestamp column into separate date and time columns

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.