How to Convert Seconds to Time in a DataFrame Using Python?

Estimated read time 2 min read

To convert seconds to time in a DataFrame column using Python, you can utilize the pandas library. Here’s an example:

import pandas as pd

# Create a sample DataFrame
data = {'seconds': [3600, 7200, 10800]}
df = pd.DataFrame(data)

# Convert seconds to time
df['time'] = pd.to_datetime(df['seconds'], unit='s').dt.time



   seconds      time
0     3600  01:00:00
1     7200  02:00:00
2    10800  03:00:00

In this example, we have a DataFrame df with a column named 'seconds' containing the number of seconds. We use the pd.to_datetime() function to convert the seconds column to a datetime object, specifying the unit as 's' for seconds. Then, we use the .dt.time accessor to extract only the time component from the datetime object.

The resulting DataFrame df will have a new column named 'time' that contains the converted time values. You can choose to keep or drop the original 'seconds' column based on your specific needs.

By default, the time component will be represented as HH:MM:SS. If you prefer a different time format, you can use the strftime() method with the desired format string to format the time component as per your requirement.

Note: The conversion to time will discard the date information, so the resulting time values will be independent of any specific date.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply