In this post, I’ll walk through how to convert a Pandas column that is in seconds and convert it to a datetime or a formatted string.
Create a Pandas DataFrame
To start, I’ll create a Pandas DataFrame with random numbers to represent my seconds column.
import pandas as pd import numpy as np import datetime as dt df = pd.DataFrame(np.random.randint(1000,size=(10, 1)),columns=['seconds'])
Convert Seconds to Datetime
Using pd.to_datetime()
we can easily convert the seconds to a datetime.
df['datetime'] = pd.to_datetime(df['seconds'], unit='s')
The new column is now formatted as a datetime. Pandas will show a full datetime representation and as a result you will see January 1st, 1970. This is because seconds are represented using Unix time and Unix time starts on January 1st, 1970. The actual date that is displayed won’t matter if all you are going after is formatting the duration. However, if you wanted a different starting point, you can apply other Pandas methods like df['datetime'] + pd.DateOffset(years=1)
.
Convert Datetime to a Formatted String Representation of Hours:Minutes:Seconds
Lastley, using .dt.strftime()
, we can convert the datetime object to a string to nicely format the duration:
df['datetime_string'] = df['datetime'].dt.strftime('%H:%M:%S')
Final Thoughts
Check out more Python tricks in this Colab Notebook or in my recent Python Posts.
Thanks for reading!