DHANANJAY CHAUBEY
DHANANJAY CHAUBEY

Reputation: 117

Date and Time Delta between two Dates

I have a table structure like below for completion of the task against name , I want to take difference between End_Time to Start_time for each name. Can anyone please suggest time how to do this with python code.

start_time  End_Time  Name
2018-08-05T00:15:00+05:30  2018-08-05T00:17:00+05:30  UM6217
2018-08-05T00:15:00+05:30  2018-08-05T00:19:00+05:30  UM28402
2018-08-05T00:15:00+05:30  2018-08-05T00:18:00+05:30  UM27746
2018-08-05T00:15:00+05:30  2018-08-05T00:16:00+05:30  UM34802

Time difference. I am using pandas dataframe to process this data

Upvotes: 1

Views: 228

Answers (2)

harpan
harpan

Reputation: 8631

You need to convert your time to pandas.datetime objects, and then simply subtract both.

df[['start_time', 'End_Time']] = df[['start_time', 'End_Time']].apply(lambda x: pd.to_datetime(x.str.split('+').str[0]))
df['diff'] = (df.End_Time - df.start_time).dt.total_seconds().div(60).astype(int) #minutes

Output:

           start_time            End_Time     Name  diff
0 2018-08-05 00:15:00 2018-08-05 00:17:00   UM6217     2
1 2018-08-05 00:15:00 2018-08-05 00:19:00  UM28402     4
2 2018-08-05 00:15:00 2018-08-05 00:18:00  UM27746     3
3 2018-08-05 00:15:00 2018-08-05 00:16:00  UM34802     1

Upvotes: 1

user96564
user96564

Reputation: 1607

Another solution can be this way too.

df['start_time'] = pd.to_datetime(df['start_time'])
df['End_time'] = pd.to_datetime(df['End_time'])

df['DifferenceInMinutes'] = (df['End_time'].sub(df['start_time'], axis = 0)) / np.timedelta64(1, 'm')

Upvotes: 0

Related Questions