Converting Time to Seconds or Minutes for an Entire Python Dataframe / CSV Column

Quick example taking a string such as ’00:25:00′ (which is 25 minutes) and converting it to 1500 seconds (for example) for an entire Python Pandas dataframe column.

First: Install required Python Packages

import pandas as pd
from csv import writer
from csv import reader

Second: Read a CSV into a Python Dataframe

df = pd.read_csv(path_to_download_default_directory + '/test.csv')

Third: Convert Time to Minutes

On line 4, I converted the seconds into minutes by diving by 60.

### Convert entire 'timeColumn' to timedelta type..
df['timeColumn'] = pd.to_timedelta(df['timeColumn'])
### Convert 'timeColumn' to minutes only.
df['columnAsMinutes'] = df['timeColumn'].dt.total_seconds() / 60
### Drop the old table.
df.drop('timeColumn', axis = 1, inplace = True)

Finally: Save Output

Let’s save our work.

df.to_csv('newData.csv', index = False)

Full Script

The full script is as follows:

Resources

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: