Home > OS >  Check whether Pandas datetime column is within a certain time range
Check whether Pandas datetime column is within a certain time range

Time:10-21

I have a Pandas dataframe with a "Datetime" column that contains a, well, a datetime :)

ColA    Datetime              ColB
----    -------------------   ----
1       2021-01-01 05:02:22   SomeVal
2       2021-01-01 01:01:22   SomeOtherVal

I want to create a new Date column that has only two rules:

1. If the "time" element of datetime is between 00:00:00 and 02:00:00 then make Date the "date" element of Datetime - 1 (the previous day)
2. Otherwise make Date the "date" element of Datetime as is

To achieve this, I'm going to have to run a check on the Datetime column. How would that look? Also, bonus points if I don't need to iterate the dataframe in order to achieve this.

CodePudding user response:

Convert values to datetimes and if time is less like 02:00:00 subtract one day in Series.mask:

from datetime import time

df['Datetime'] = pd.to_datetime(df['Datetime'])

df['Datetime'] = df['Datetime'].mask(df['Datetime'].dt.time <= time(2, 0, 0), 
                                     df['Datetime'] - pd.Timedelta('1 day'))
print (df)
   ColA            Datetime          ColB
0     1 2021-01-01 05:02:22       SomeVal
1     2 2020-12-31 01:01:22  SomeOtherVal
  • Related