Home »
Python »
Python Programs
Convert timedelta64[ns] column to seconds in Pandas DataFrame
Learn how to convert timedelta64[ns] column to seconds in Pandas DataFrame in Python?
Submitted by Pranit Sharma, on February 11, 2023
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.
Timedelta
Timedelta is the method used for representing differences in time, which is expressed in different units, like hours, minutes, and seconds.
The Timedelta method takes a string inside it as a parameter in which we simply define the time in human language and it converts that string to measure time differences.
Problem statement
Suppose that we are given a pandas dataframe of the Timedelta column and we need to convert this time in only seconds.
Converting timedelta64[ns] column to seconds
For this purpose, we will simply change the data type of the column from timedelta64[ns] to timedelta64[s].
Let us understand with the help of an example,
Python program to convert timedelta64[ns] column to seconds in Pandas DataFrame
# Importing pandas package
import pandas as pd
# Import datetime
import datetime
# Import numpy
import numpy as np
# Creating a dataframe
df = pd.DataFrame({'col':['56:03:172','26:13:172','12:07:172']})
# Display Original DataFrame
print(" Original DataFrame:\n",df,"\n")
# Converting the columns to timedelta
df['col'] = pd.to_timedelta(df['col'])
# Converting the time only in seconds
df['col'] = df['col'].astype('timedelta64[s]')
# Display modified dataframe
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »