Home > Enterprise >  Add time delta for 2 columns based on the condition on 1 column in pandas
Add time delta for 2 columns based on the condition on 1 column in pandas

Time:01-06

I have a dataframe

df = pd.DataFrame([["A","9:00 AM","10:20 AM"],["A","11:12 AM","12:32 PM"],["A","1:03 PM","1:33 PM"],["A","1:34 PM","2:44 PM"],["B","9:00 AM","12:20 PM"],["B","12:56 PM","1:06 PM"],["B","1:07 PM","1:17 PM"],["B","1:18 PM","1:28 PM"]],columns=["id","start_time","end_time"])
id  start_time  end_time
A    9:00 AM    10:20 AM
A   11:12 AM    12:32 PM
A    1:03 PM     1:33 PM
A    1:34 PM     2:44 PM
B    9:00 AM    12:20 PM
B   12:56 PM     1:06 PM
B    1:07 PM     1:17 PM
B    1:18 PM     1:28 PM

I want to add time delta 1 hour for each row of the columns start_time and end_time where start_time >= 12:30 PM.

Expected Output:

df_out = pd.DataFrame([["A","9:00 AM","10:20 AM"],["A","11:12 AM","12:32 PM"],["A","2:03 PM","2:33 PM"],["A","2:34 PM","3:44 PM"],["B","9:00 AM","12:20 PM"],["B","1:56 PM","2:06 PM"],["B","2:07 PM","2:17 PM"],["B","2:18 PM","2:28 PM"]],columns=["id","start_time","end_time"])
id  start_time  end_time
A    9:00 AM    10:20 AM
A   11:12 AM    12:32 PM
A    2:03 PM     2:33 PM
A    2:34 PM     3:44 PM
B    9:00 AM    12:20 PM
B    1:56 PM     2:06 PM
B    2:07 PM     2:17 PM
B    2:18 PM     2:28 PM

How to do it?

CodePudding user response:

You can use:

# Convert to datetime
start_time = pd.to_datetime(df['start_time'])
end_time = pd.to_datetime(df['start_time'])

# Boolean mask
cond = start_time >= pd.Timestamp('12:30')
offset = pd.DateOffset(hours=1)

# Update values
df.loc[cond, 'start_time'] = start_time[cond].add(offset).dt.strftime('%-I:%M %p')
df.loc[cond, 'end_time'] = end_time[cond].add(offset).dt.strftime('%-I:%M %p')

Output:

>>> df
  id start_time  end_time
0  A    9:00 AM  10:20 AM
1  A   11:12 AM  12:32 PM
2  A    2:03 PM   2:03 PM
3  A    2:34 PM   2:34 PM
4  B    9:00 AM  12:20 PM
5  B    1:56 PM   1:56 PM
6  B    2:07 PM   2:07 PM
7  B    2:18 PM   2:18 PM
  • Related