Adding hour to date/time in pandas using conditions

Viewed 168

I have a dataframe with a Date/Time column

0    2020-01-07 09:00:00
1    2020-01-15 13:00:00
2    2020-01-22 14:00:00
3    2020-01-30 09:00:00
4    2020-02-05 14:00:00
5    2020-02-12 10:00:00
6    2020-05-12 07:00:00
7    2020-05-12 08:00:00
8    2020-05-12 09:00:00
9    2020-05-12 10:00:00
10   2020-05-12 11:00:00
11   2020-05-12 12:00:00
12   2020-05-12 13:00:00
13   2020-05-12 14:00:00
14   2020-05-12 15:00:00
15   2020-05-12 16:00:00
16   2020-07-02 08:00:00
17   2020-07-02 09:00:00
18   2020-07-02 10:00:00
19   2020-07-02 11:00:00
20   2020-07-02 12:00:00

what I am trying to do is to add 2 hours to the time where the date is between 3/14/2020 & 11/07/2020, and add 1 hour to the time everywhere else. I have been able to add the hour by using the following:

df['Date/Time'] = df['Date/Time'] + pd.DateOffset(hours=1)

however, I can't seem to figure out how to do it via df.loc. what I have tried:

df.loc[(df['Date/Time'] >= start_date) & (df['Date/Time'] <= end_date), ['Date/Time']] = (['Date/Time'] + pd.DateOffset(hours=1))

I have also tried iterating over the dataframe using For and nested IF statements, but that throws me the following error.

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

any help would be appreciated. Thank you

1 Answers

Let's try:

start_time, end_time = '3/14/2020', '11/07/2020'

df['Date/Time'] += np.where(df['Date/Time'].between(start_time, end_time),
         pd.Timedelta('2H'),
         pd.Timedelta('1H')
        )

start_time, end_time = 314, 1107

month_day = df['Date/Time'].dt.month * 100 + df['Date/Time'].dt.day
df['Date/Time'] += np.where(month_day.between(start_time, end_time),
     pd.Timedelta('2H'),
     pd.Timedelta('1H')
    )
Related