1

I have a timedelta object e.g: 0 days 00:03:56.571428571 I would like to save it into only time format e.g: 00:03:56 Basically, I want to remove days and miliseconds part from timedelta object.

Also, please note its just a 'Timedelta' object(which is an average of differences of consecutive 'datetime' objects from a pandas data frame) NOT a 'datetime.timedelta'.

Could you please guide me? how can I achieve this output?

Thank you.

sudha11
  • 23
  • 8

1 Answers1

0

you can use the below code for two columns with datetime values (or you can use apply on a single column that contains the already calculated timedelta object). Use the components of the timedelta to get the hours, minutes and seconds and then use time from datetime to return the object with the hours, minutes, seconds and ignores the rest.

import pandas as pd
from datetime import time

A = [pd.to_datetime('2020-10-19 20:12:10', format='%Y-%m-%d %H:%M:%S'),
     pd.to_datetime('2020-11-09 20:10:04', format='%Y-%m-%d %H:%M:%S')]
B = [pd.to_datetime('2020-10-12 16:16:14', format='%Y-%m-%d %H:%M:%S'),
     pd.to_datetime('2020-09-01 20:22:04', format='%Y-%m-%d %H:%M:%S')]

df = pd.DataFrame(data =[A,B], columns=['Date1','Date2'])



df['Timeinterval'] = (df['Date1']-df['Date2']).apply(lambda x:time(x.components[1],x.components[2],x.components[3]))
df