Pandas Convert Datetime to Seconds

  • Post author:
  • Post category:Pandas
  • Post last modified:November 21, 2023

We can use pandas.Series.dt.second attribute to convert the Datetime column to seconds in Pandas. DateTime is a collection of a date and a time in the format of “YYYY-MM-DD HH:MM:SS” where YYYY-MM-DD is referred to as the date and HH:MM:SS is referred to as Time. We can convert the DateTime (date) column to seconds in pandas in several ways. In this article, I will explain how to convert the Datetime column to seconds using dt.second, pandas.DatetimeIndex, dt.strftime(), and apply() functions.

If the data is not in Datetime type, you need to convert it first to Datetime by using the pd.to_datetime() method.

Related: convert the datetime column to month and year at a time in Pandas and extract only the year from the Datetime column of Pandas DataFrame

1. Quick Examples of Convert Datetime to Seconds

If you are in a hurry, below are some quick examples of how to convert the DateTime column to Seconds.


# Below are the quick examples

# Example 1: Use Datetime.strftime() Method to extract second
df['second'] = df['InsertedDate'].dt.strftime('%S')

# Example 2: Convert datetime to seconds using dt.second
df['second'] = df["InsertedDate"].dt.second

# Example 3: Using pandas.DatetimeIndex() to extract second
df['second'] = pd.DatetimeIndex(df['InsertedDate']).second

# Example 4: Use DataFrame.apply() with lambda function and strftime()
# get the second from the datetime column
df['second'] = df['InsertedDate'].apply(lambda x: x.strftime('%S')) 

2. Pandas Convert Seconds using Datetime.strftime()

Let’s create Pandas DataFrame with the column of Datetime in the form of hours, minutes, and seconds and use Pandas attributes and functions to extract the seconds from a given datetime column.


import pandas as pd
import numpy as np
Dates = ['2021-11-15 21:04:15','2020-05-04 22:04:10','2018-01-26 15:23:14','2019-02-18 10:05:18','2021-12-10 15:13:21']
Courses =["Spark", "PySpark", "Hadoop", "Python", "Pandas"]
df = pd.DataFrame({'InsertedDate': pd.to_datetime(Dates)}, index=Courses)
print("DataFrame:\n", df)

Yields below output.

pandas convert datetime seconds

strftime() method takes the datetime format and returns a string representing the specific format. You can use %S to extract seconds from the datetime column of pandas DataFrame.


# Use Datetime.strftime() Method to extract second
df['second'] = df['InsertedDate'].dt.strftime('%S')
print("Get seconds from datetime column:\n", df)

Yields below output.

pandas convert datetime seconds

3. Convert Pandas Datetime to Seconds using dt.second

You can use pandas.Series.dt.second to get seconds from the datetime column of a given DataFrame and this function returns a series object. Assign this object as a column to DataFrame and get the given DataFrame along with the second columns.


# Convert datetime to seconds
df['second'] = df["InsertedDate"].dt.second
print("Get seconds from datetime column:\n", df)

Yields below output.


# Output:
# Get seconds from datetime column:
               InsertedDate  second
Spark   2021-11-15 21:04:15      15
PySpark 2020-05-04 22:04:10      10
Hadoop  2018-01-26 15:23:14      14
Python  2019-02-18 10:05:18      18
Pandas  2021-12-10 15:13:21      21

4. Use pandas DatetimeIndex() to Convert Second

Also, to convert the pandas Datetime column to seconds, use the DatetimeIndex.second attribute. Note that this method takes a date as an argument.


# Using pandas.DatetimeIndex() to extract second
df['second'] = pd.DatetimeIndex(df['InsertedDate']).second
print("Get seconds from datetime column:\n", df)

Yields the same output as above.

5. Use DataFrame.apply() With Lambda Function and strftime()

Let’s see how to get the seconds column from the datetime column of the given DataFrame by using Pandas DataFrame.apply() and lambda function. Let’s pass the lambda function as an argument of the apply() function and then call the strftime() with the lambda function, it will extract the seconds from the datetime column.


# Use DataFrame.apply() with lambda function and strftime()
# get the seconds from Datetime column
df['second'] = df['InsertedDate'].apply(lambda x: x.strftime('%S')) 
print("Get seconds from datetime column:\n", df)

Yields below output.


# Output:
# Get seconds from datetime column:
               InsertedDate Second
Spark   2021-11-15 21:04:15     15
PySpark 2020-05-04 22:04:10     10
Hadoop  2018-01-26 15:23:14     14
Python  2019-02-18 10:05:18     18
Pandas  2021-12-10 15:13:21     21

Conclusion

In this article, I have explained how to convert Pandas DateTime column to second by using Pandas.Series.dt.second, pandas.Series.dt.strftime(), pandas.DatetimeIndex(), and DataFrame.apply() methods with examples.

Happy Learning !!

References

Naveen

I am a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, I have honed my expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. My journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. I have started this SparkByExamples.com to share my experiences with the data as I come across. You can learn more about me at LinkedIn

Leave a Reply

You are currently viewing Pandas Convert Datetime to Seconds