Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i subtarct 2 time columns with each other in Python?

I have a column Start and HT where both are Object Datatype:
The output which is needed is (HT – Start) in minutes.

I try to convert them to datetime through pd.to_datetime but it throws error
TypeError: <class ‘datetime.time’> is not convertible to datetime

Start HT
09:30:00 09:40:00
09:30:00 09:36:00
09:30:00 09:50:00
09:30:00 10:36:00

Expected Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Start HT diff(in minutes)
09:30:00 09:40:00 10
09:30:00 09:36:00 6
09:30:00 09:50:00 20
09:30:00 10:36:00 66

Please help.

>Solution :

You should fisrt convert dates using pd.to_datetime()

df['Start'] = pd.to_datetime(df['Start'], format='%H:%M:%S').dt.time.apply(str)
df['HT'] = pd.to_datetime(df['HT'], format='%H:%M:%S').dt.time.apply(str)
df['diff(in minutes)'] = (pd.to_timedelta(df['HT']) - pd.to_timedelta(df['Start'])).dt.total_seconds() / 60
print(df)

      Start        HT  diff(in minutes)
0  09:30:00  09:40:00              10.0
1  09:30:00  09:36:00               6.0
2  09:30:00  09:50:00              20.0
3  09:30:00  10:36:00              66.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading